Search code examples
segmentation-faultnewlinefgets

Getting segmentation fault while comparing the \n of a string that red by fgets() in C language


I am writing a program to reverse the words in a string, i.e., "abc def" to "def abc".

I read the input using fgets(). I am using:

for(j = i;((buff[i] != ' ') || (buff[i] != '\n'));i++ );

to identify the space or end of line.

But I am ending up with a segmentation fault.

With checking for space alone, everything is working fine.

Please help me on this.


Solution

  • ((buff[i] != ' ') || (buff[i] != '\n'))
    

    This means "keep going while the character is not a space or is not a newline".

    Since a character can never be both a space and a newline at the same time, at least one of those sub-conditions will always be true. Lets take a few examples:

    value    (value != ' ')  (value != '\n')  or'ed result
    -------  --------------  ---------------  ------------
    space        false           true             true
    newline      true            false            true
    'A'          true            true             true
    

    Hence you have an infinite loop which is almost certainly what's causing your problem.

    I suggest you replace the || with the more correct && as in "keep going while the character is both not a space and not a newline":

    value    (value != ' ')  (value != '\n')  and'ed result
    -------  --------------  ---------------  -------------
    space        false           true             false
    newline      true            false            false
    'A'          true            true             true