daavid245 daavid245 - 3 months ago 14
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;

Sleep(10);

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);

Sleep(10);

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";
target->Clean();
break;
}

Sleep(300);
}


Main receive code:

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

Sleep(1);
}


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

Answer

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.