繁体   English   中英

fscanf分段错误-C

[英]fscanf Segmentation fault - C

我在尝试使用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;
}

在对strlen(temp)的调用中, temp具有未定义的内容。

而是使用char temp[100] = {0}; 并且根本不使用memset

strlen函数遵循以下原则:

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

换句话说,它将返回遇到的第一个空字符的位置。 如果尚未初始化字符串,则指针可能会从数组边界增加并进入进程内存的其他部分,以查找空终止符(这使它成为段错误)。

要解决此问题,请使用sizeof(temp)替换memset的参数。

这是与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;
}

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

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

暂无
暂无

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

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