> I have to say that vart and Salem are both way, way, way off base when they claim the point is to cover a bug or because the use of recv is "incorrect".
Example
Code:
memset( buff, 0, sizeof buff )
recv( sock, buff, sizeof buff, 0 );
If recv() actually FILLS the buffer, then two things
a) the memset was a complete and utter waste of time,
b) the resulting buffer STILL DOES NOT have a \0, nor does it have room for one either.
In other words, a total loss.
Consider
Code:
// drop the -1 if you're not interested in making a string
n = recv( sock, buff, sizeof buff - 1, 0 );
if ( n > 0 ) {
buff[n] = '\0'; // if you really want a \0 string
// do stuff with 'n' bytes
}
Done this way, the need for memset hokus-pokus vanishes, the buffer is correctly \0 terminated in a single instruction (or two, but certainly much more efficiently than memset), if that is what you want to do.
In any event, the real size of the received data is available to make sure you can do the right thing.
> My preference would be to add or at least check for the null terminator after the recv, which seems more optimal.
Who said that you were going to get a \0 from recv()
Who said that you were going to receive it in a timely manner, even if it was sent?
It's quite simple. Use the return result of the function properly, and you're not going to go wrong.