简体   繁体   English

fscanf分段错误-C

[英]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. 我在尝试使用fscanf从文件读取为字符串时遇到分段错误错误,我们将不胜感激。

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. 在对strlen(temp)的调用中, temp具有未定义的内容。

Instead, use char temp[100] = {0}; 而是使用char temp[100] = {0}; and don't use memset at all. 并且根本不使用memset

The strlen function does something along these lines: strlen函数遵循以下原则:

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) . 要解决此问题,请使用sizeof(temp)替换memset的参数。

It is problem related to strlen function, you can fix it like this: 这是与strlen函数有关的问题,您可以像这样修复它:

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)); 摆脱memset(temp, 0, strlen(temp));

Replace char temp[100]; 替换char temp[100]; with char temp[100] = {}; 使用char temp[100] = {};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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