I am trying to write a client/server program in C for a homework assignment. What should happen is:
Connection is made
Server waits for client to send a message
client asks user for a message, assigns it to a string, and then sends it to the server. This is done in the following code on the client:
while(1){
/* prepare message */
printf ("Please enter the message: ");
bzero (buffer, BUFFERLENGTH); //BUFFERLENGTH is defined as 256
fgets (buffer, BUFFERLENGTH, stdin);
/* send message */
n = write (sockfd, buffer, strlen(buffer));
if (n < 0)
error ("ERROR writing to socket");
bzero (buffer, BUFFERLENGTH);
}
now, my problem is that this code is sending a bit of gibberish. As far as I can tell, buffer is not being emptied, or is not always BUFFERLENGTH long, so is random junk is being read from the stack?
The server receives the message and then prints it. If the client program scans in "actual string I input" then the server will output something similar to:
actual string I input @&^%~& although the terminal output is more full of nonprintable characters, and also line breaks.
Code for the server is:
n = read (*newsockfd, buffer, BUFFERLENGTH -1);
printf("buffer = %s\n",buffer);
if (n < 0)
error ("ERROR reading from socket");
This does not happen when I remove the while loop though!
I’ve read about bzero and I know it’s deprecated, and I should use memset; however I tried doing that, with: memset(buffer,0,BUFFERLENGTH); and the problem still happens.
Any explanation of why buffer has gibberish appended to it?
Edit
buffer is declared in the client by: char buffer[BUFFERLENGTH];
`
printf("%s", ...)expects a 0-terninated string.So you should append a
0to the end of the buffer you received.Update:
Assuming buffer is defined like:
To add a
0to the last array entry do like so:A more generic approach whould (although more costly) be to zero out the whole receive buffer prior to reading into it: