简体   繁体   中英

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;
}

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

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

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

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;
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM