Search code examples
cfgets

fgets, seg fault and array of strings


I'm having trouble getting this short program to work. It's not complete but I want to solve a seg fault I'm getting at compilation. The gist of what's there is pretty much:

To reads a (sub)string on the command line and search for that (sub)string in every 'word' on stdin. Every word that contains this (sub)string is printed. If no match can be found, an appropriate message is output. Also, if there is less or more than one command-line argument, a usage-message is output.

I understand a seg fault can arise from an attempt to access an index that doesn't exist or infinite loops. A little bit of bug testing shows that the problem does lie in the while loop, but I can't figure out why.

The result is when I input: ./match ant < match.data into the command line, with match.data holding

fantastic dog x gooblygooblygoo antx xant ant anananananananananananan

When fgets reaches the end of match.data, does it not return NULL and the loop terminated?

Thanks!

enter image description here


Solution

  • There are two problems with your code:

    1. You use an uninitialized pointer in the fgets call (the pointers in the array are all uninitialized)

    2. You're doing sizeof in a pointer, which returns the size of the pointer and not what it points to.

    To solve the first problem is to allocate memory for the pointers inside the array. This can either be done by allocating dynamically (using e.g. malloc) or make it an array of arrays.

    When the first point is solved, it's easy to solve the second point, as you then have the size of the strings.


    Reading your code closer, you actually initialize the first pointer in the array, when you make it point to a constant (read-only) array of five characters, the character literal "NOPE". Besides having undefined behavior when using uninitialized data, you another case here when you try to write into read-only memory (and possibly write beyond the bounds if the first input is more than four characters).