newprogrammer
newprogrammer

Reputation: 620

fscanf Segmentation fault - C

I am getting a segmentation fault error while trying to use fscanf to read from a file into a string, any help would be greatly appreciated.

int main()
{
    char temp[100];
    FILE *fp = fopen("test.txt", "r");

    if (fp == NULL)
    {
        printf("error");
    }

    memset(temp, 0, strlen(temp));

    while (fscanf(fp,"%s", temp)==1)
    {

    }

return 0;
}

Upvotes: 2

Views: 609

Answers (4)

Govind Parmar
Govind Parmar

Reputation: 21532

The strlen function does something along these lines:

int strlen(char *s)
{
    int len = 0;
    while(*s++) len++;
    return len;
}

In other words, it will return the location of the first null character it encounters. If you haven't already initialized your string, then the pointer will probably get incremented out of the array bounds and into some other part of the process' memory in search of the null terminator (which makes it segfault).

To address this issue, replace the argument to memset with sizeof(temp).

Upvotes: 3

Beta Carotin
Beta Carotin

Reputation: 1679

In the call to strlen(temp), temp has undefined contents.

Instead, use char temp[100] = {0}; and don't use memset at all.

Upvotes: 3

It is problem related to strlen function, you can fix it like this:

int main()
{
    char temp[100];
    FILE *fp = fopen("test.txt", "r");

    if (fp == NULL)
    {
        printf("error");
    }

    memset(temp, 0, sizeof(temp)); //use sizeof instead of strlen is enough

    while (fscanf(fp,"%s", temp)==1)
    {

    }

return 0;
}

Upvotes: 1

Dellowar
Dellowar

Reputation: 3352

Get rid of memset(temp, 0, strlen(temp));

Replace char temp[100]; with char temp[100] = {};

Upvotes: -2

Related Questions