daavid245 daavid245 - 11 months ago 75
C++ Question

C++ Winsock2 recv junk

So I am writing a Windows chat and for testing purposes my client program sends a "hello" message to the server every 300 ms.

First couple messages come good but then like for no reason they start to become junk- screenshot

Obviously I want to fix it and I seek for your help :) Here is my code:

Send function:

bool Target::Send(char *message)
int length = strlen(message);
int result = send(this->ccSock, (char*)&length, sizeof(int), 0);
if (result <= 0)
return false;


result = send(this->ccSock, message, length, 0);
return ((result > 0) ? true : false);

Receive function:

Message Server::Receive(SOCKET socket)
int length = 0;
int result = recv(socket, (char*)&length, sizeof(int), 0);


char *rcvData = new char[length];
result = recv(socket, rcvData, length, 0);

return { rcvData, result };

Message struct:

struct Message {
char *msg;
int size;

Main send code:

while (true)
if (!target->Send("hello"))
cout << "Connection broken\n";


Main receive code:

while (target.sock)
Message message = server->Receive(target.sock);
if (message.size > 0)
cout << message.msg << " (" << message.size << ")\n";
cout << "Target disconnected\n";


I would really appreciate your help as well as explanation why this is happening!

Answer Source

Your buffer is not null terminated. So when you are trying to print it using std::cout buffer overrun occurs. Correct version of receive code should be:

char *rcvData = new char[length+1];
result = recv(socket, rcvData, length, 0); 
rcvData[length] = '\0';

Also you never free allocated memory buffer, so your code leaks it on each Receive call.