advertisement

Article:
  Networking and the BSD Sockets API
Subject:   bug in client.c
Date:   2003-02-02 22:11:50
From:   anonymous2
Very nice article. One bug you may want to rectify in your example:


The test for n < 0 will never been seen, since the test in the while statement:


while ( n = read( sockfd, buffer, BufferSize-1) ) {
buffer[n] = 0;
printf("%s", buffer );
}
if ( n < 0 ) {
perror( "read" );
exit(1);
}


is true whether n > 0 or n < 0. Further, if n < 0, the "buffer[n] = 0" statement could in principle lead to a crash of the client program.


You should probably have for the while comparison:


while ( (n = read( sockfd, buffer, BufferSize-1)) > 0 ) {
buffer[n] = 0;
printf("%s", buffer );
}


I prefer explicit logic tests as this tends to help prompt one's thinking to avoid this type of errors.


Carrick Talmadge
clt@olemiss.edu