Thread: Some help for a newbie.

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    Quote Originally Posted by algorism View Post
    You've accidentaly used sizeof instead of strlen in removing the newline. Should be:
    Code:
    message[strlen(message)-1] = '\0'; // Ensure '\0' termination.
    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.

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    Quote Originally Posted by c99tutorial View Post
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Hello, I am a newbie and so I have a newbie question;)
    By piratemonkey247 in forum C Programming
    Replies: 4
    Last Post: 12-20-2012, 10:59 AM
  2. Newbie with Very Newbie Question
    By Jedi_Mediator in forum C++ Programming
    Replies: 18
    Last Post: 07-01-2008, 08:00 AM
  3. C++ newbie / linux not so newbie question
    By goldmonkey in forum C++ Programming
    Replies: 7
    Last Post: 12-13-2003, 12:27 PM
  4. Newbie but not really
    By atanpoco in forum C++ Programming
    Replies: 10
    Last Post: 05-13-2003, 09:22 AM
  5. Newbie needs help
    By Getintothegame in forum Windows Programming
    Replies: 4
    Last Post: 05-04-2003, 02:07 AM

Tags for this Thread