S
S
sddvxd2018-04-21 03:40:10
C++ / C#
sddvxd, 2018-04-21 03:40:10

Why does the WinSock receive buffer fill up with garbage?

Hello.
Sources taken from MSDN:

do {
      iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
      if (iResult > 0) {
        iSendResult = send(ClientSocket, recvbuf, iResult, 0);
        if(iSendResult==SOCKET_ERROR){
          printf("send failed with error: %d\n", WSAGetLastError());
          closesocket(ClientSocket);
          WSACleanup();
        }
        for (int i = 0; i < iResult; i++) {
          std::cout << recvbuf[i];
        }
      }
      else if (iResult == 0) {
        //std::cout << "Connection closing...\n";
        std::cout << std::endl;
      }
      else {
        printf("recv failed with error: %d\n", WSAGetLastError());
        closesocket(ClientSocket);
        WSACleanup();
        std::cout << "Error in receive\n";
      }
    } while (iResult > 0);

The problem is that for some reason recvbuf contains some kind of garbage, although iResult, let's say if I send 4 bytes to the server - also contains the number 4
And if I look at strlen(recvbuf) I get 16. Where does such a tail come from? When outputting recvbuf, the first 4 bytes are output and then garbage

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
res2001, 2018-04-21
@sddvxd

And if I look at strlen(recvbuf), I get 16. Where does such a tail come from?

In recvbuf you get not a c-string, but an array of bytes, it makes no sense to apply string functions to an array of bytes.
The difference between a c-string and an array is that the string ends with a terminating null, while in a byte array you must know the length of the array. In the c-string, the character 0 cannot be in the body of the string itself, only as a terminal character, in the byte array 0 - the same equal data element as all the others, can be anywhere in the array or not at all.
You are also lucky that it gives out 16 bytes instead of 4, it could well turn out that there would not be a zero byte in a sufficiently long section of memory, then there would just be a crash from the program or some hard-to-diagnose glitches.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question