I am trying to append ” ” to messages in a chat program. In the below example buf is a character array holding the message. The weird thing is when I send this down a socket with write() it sends it in 2 bursts. The first burst is the correct message, then a second burst is 2-3 random non alphabetic ascii characters. Any idea what is up? When I just send buf down the socket, it works correctly.
char nickmsg[550];
strcpy(nickmsg, "<");
strcat(nickmsg, username);
strcat(nickmsg, "> ");
strcat(nickmsg, buf);
write(sd, nickmsg, sizeof(nickmsg));
You don’t want sizeof(nickmsg), you want strlen(nickmsg). Using sizeof(nickmsg), you’re sending everything that’s in that buffer, not just the string you built in it. If it’s only the chars in the string you want to send, you need to calculate the length of what’s in there. (btw, there are more efficient ways to create strings than repeated strcats)