-2

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;
}
Noam M
  • 3,156
  • 5
  • 26
  • 41

2 Answers2

5

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().

Noam M
  • 3,156
  • 5
  • 26
  • 41
1

I think you should check s:

int inTable(const char *s) 
{
     if (s == NULL)
     {
          return 0;
     }

     // invoke strcmp
}

make sure const char *s is terminated with '\0

Noam M
  • 3,156
  • 5
  • 26
  • 41
finesse
  • 117
  • 6