【问题标题】:fscanf Segmentation fault - Cfscanf 分段错误 - C
【发布时间】:2017-03-29 15:52:19
【问题描述】:

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

【问题讨论】:

  • 输入文件的内容? (它可能有一个超过 99 个字符的字符串吗?)
  • 除了其他 cmets 和答案:memset(temp, 0, strlen(temp)); 根本不需要,因为无论如何你 fscan 到 temp。
  • @MichaelWalz 我仍然认为为了安全起见,在char 数组的开头至少有一个空终止符是个好主意。
  • @BetaCarotin memset(temp, 0, strlen(temp)) 提供什么“安全”?如果fscanf(fp,"%s", temp)==1 不为真,则不指定temp 的内容以保留零。如果有的话,代码应该使用 wdith 限制 fscanf(fp,"%99s", temp) 来表示“安全”。
  • @chux 无。我说的是如果有char数组,前面应该有0。

标签: c segmentation-fault scanf


【解决方案1】:

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

改为使用char temp[100] = {0};,完全不要使用memset。

【讨论】:

  • 注意strlen(temp) 在这种情况下会返回零,所以memset 不会做任何事情。此外,temp 在调用fscanf 之前不需要初始化。
  • @DrewMcGowen 谢谢,我明确提到删除对memset的调用。
  • @SanchkeDellowar 这是我在回复评论时所做的。
  • 注意:char temp[100] = {}; 在 ISO C 中不起作用。char temp[100] = {0}; 将是可移植的方式。
【解决方案2】:

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

将char temp[100]; 替换为char temp[100] = {};

【讨论】:

  • 你复制了我的答案,甚至懒得说明代码无效的原因。
  • 您实际上不需要替换声明,因为fscanf 不关心内容。
【解决方案3】:

strlen 函数执行以下操作:

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

换句话说,它将返回它遇到的第一个空字符的位置。如果你还没有初始化你的字符串,那么指针可能会从数组边界递增到进程内存的其他部分以搜索空终止符(这使它成为段错误)。

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

【讨论】:

  • 虽然您确实解释了代码存在分段错误的原因,但恕我直言,您应该详细说明并演示如何解决问题。
  • @BlueMoon93 已修复 :)
【解决方案4】:

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

【讨论】:

    猜你喜欢
    • 2015-02-09
    • 2011-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多