[Winsock2] Extra characters at the end of string

Hi guys. Straight to the point, here's a piece of my code:

Client:

char buffer[32];
for(unsigned i = 0; i < 32; i++)
buffer[i] = i + 64;

send(socket, buffer, sizeof(buffer), 0);

receive(socket, buffer, 32, 0);


Server:

char buffer[32]

recv(socket, buffer, 32, 0);

send(socket, buffer, sizeof(buffer), 0);


Now, it successfully transfers the string but adds weird characters at the end of it. If i understood correctly there has to be \0 at end of string so if i add

buffer[31] = '\0'; it works.

But, do i have to add that and sacrifice 1 character or is there any way around it?
If you need 32 actual characters to be sent, is there anything stopping you from doing char buffer[33]; and setting the char at index 32 to \0? You could then use the chars at indices 0-31 for your message. Let me know if that isn't what you meant, or if there is some reason why that wouldn't work.
Well i can do that. I was just wondering if i could do that without having to extend/reduce size of my string/buffersize. Thanks for the idea tho i didnt really think of that.
I was just wondering if i could do that without having to extend/reduce size of my string/buffersize.
Sure, you just can't pass the buffer to a function that expects '\0' at the end of the string.
Topic archived. No new replies allowed.