0

I remember reading the explanation on the use of this line of code, but I've read so many books on sockets for the past week that I can't find it anymore.

I do remember in the book, they wrote their code using =\0, then said it would be better to have it at 1

I tried searching it, but had no luck, this is a piece of the code I'm reading where it is used

 nread = recv(newsock, buffer, 25, 0);
 buffer[nread] = '\0';
user2644360
  • 71
  • 1
  • 2
  • 9
  • 3
    I hope `buffer` is at least 26 long... And the code should definitely check for `nread == -1` before proceeding. (Or rather that it is not -1 before setting the end marker. – Mats Petersson Aug 04 '13 at 00:37
  • @Borgleader I didn't know what it was called before they told me. So I couldn't search for it properly. – user2644360 Aug 04 '13 at 00:38

3 Answers3

5

It turns the received buffer into a NUL-terminated C-string, that you can use with strlen, strcpy, etc. I assume the code you show is for illustrative purposes only, not production code, because you're not checking the return value of recv, which can be -1. If that happens it will cause memory corruption.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
zentrunix
  • 2,098
  • 12
  • 20
2

This is the C/C++ null terminator which indicates the end of content in a character array.

http://en.wikipedia.org/wiki/Null-terminated_string

Benjamin Pack
  • 365
  • 2
  • 3
0

It is to signify that the string ends at that byte. In this case the last one.

\0 is the null character.

So you don't get garbage like "This is my message.aG¤(Ag4h98av¤"G#¤". Just imagine there's a \0 at the end of that string.

When dealing with networking, you usually want to send data like integers, and the most common practice is to send it in binary and not plaintext. An integer may look like "$%\0n" for example. 4 bytes, but the third one is a \0. So you have to take into account that there can be a \0. Therefore you should not store binary representation of data as a string, but rather as a buffer/stringstream.

Of course, maybe you don't want to print out the binary representation of it. But you have to keep it in mind. Maybe you want to print it out, who knows.