Search code examples
cstringcomparestrcmp

strcmp() not comparing


Hello everybody, I'm a newbie and I'm doing a code that the principal aim is to print a number if two strings are equal. First string is obtained from a file and the second one is the string to be compared with.

The code:

int main()
{
char *string[2];
FILE *stream;
stream = fopen("REL","r");
if( (stream = fopen("REL","r")) == NULL)
{  
    printf("Can't open %s\n","REL");
    exit(1);
}
for(int i=0;i<92;i++)
{
    fscanf(stream,"%s",&string);
    if( strcmp("20", *string) == 0 )
    {
        printf("%d",20);
    }
}
fclose(stream);
}

and... when I tested on shell, it promp to me:

~/CM$ ./file2 
Segmentation fault (core dumped)

I might be doing a silly mistake. But, as a newbie, I cannot figure out whats is going wrong with the script.


Solution

  • string is an unitialised array of 2 char*. The fscanf is attempting to write to memory where is should not. Declare string as an array of char:

    char string[256];
    

    and:

    fscanf(stream, "%255s", string); /* Limit number of
                                        chars read to prevent buffer overrun. */