Originally Posted by
c99tutorial
fgets is not guaranteed to write a '\0' byte to the buffer, so strlen is not guaranteed to work. Hence this line:
Code:
message[sizeof(message)-1] = '\0'; // Ensure '\0' termination.
After that, you can safely use strlen on message, but unfortunately not before.
Then it's even more of a half-assed solution than I originally thought. The only way fgets won't 0-terminate the string is if it returns NULL, so the obviously superior solution is to test its return value. Your "solution" simply "ensures" the 0-termination of a string of garbage. Useless.
Code:
if (fgets(message, sizeof message, stdin) == NULL)
; // handle eof or other problem
else
message[strcspn(message, "\n")] = 0; // remove newline