Question

int resp = recv(s, buf, len, flags);

if(resp == 18) {
    char data[18];
    strcpy(data, buf);
    ...
}

I expect strlen(data) to be equal 18, but it isn`t. What did I miss?

Was it helpful?

Solution

If your data contains a zero-byte \0, then strlen will only give you the length of the string up to the terminator. If data does not have a terminator, then strlen will continue searching through whatever memory it happens to be at. This is commonly used in buffer overflow attacks.

OTHER TIPS

I think what Joe is trying to say is your code isn't bullet-proof, starting with the number bytes read and copying the data into the data array.

int resp = recv(s, buf, len, flags);
if(resp > 0) 
{
  // ! This code assumse that all the data will fit into 18 bytes.
  char data[18];  
  memset(data, 0, sizeof(data));  

  // ! As Joe warned above, this code assumes there's a null terminating 
  // ! character in the buf you received.

  strcpy(data, buf);  // consider memcpy if binary data (i.e. not strings)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top