Search code examples
cdebuggingsegmentation-faultgdbstrcmp

Segmentation fault strcmp in c


I'm trying to run a program in c that takes in a text file and string from the user and then searches the file for that string. It keeps getting a segmentation fault and gdb is pointing me towards this function but I am not sure what the problem is. I am pretty sure it has something to do with the strcmp call but I am not sure. Any help with this issue would be greatly appreciated.

int inTable( const char *s )
{
    int i;

    for( i=0; i<numLines; ++i )
    {
        if( strcmp( st[i], s ) == 0 )
                return 1;
    }

    return 0;
}

Solution

  • You should check that you properly use strcmp(), the API is:

    int strcmp(const char *str1, const char *str2)
    

    You must:

    1) Validate that st[i], your first argument is a pointer.

    2) Make sure that st[i] & s has the Null terminator '\0'`.

    3) Check that st[i] & s pointing to an allocated place in the memory before calling strcmp().