【问题标题】:two consecutive fgets seg faults两个连续的 fgets 段错误
【发布时间】:2015-03-30 02:39:07
【问题描述】:

我目前正在尝试读取两个字符串 s 和 t,它们将被输入到 stdio。它们将在不同的行中输入。

以下代码段错误。

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    char t[5000000];
    char s[5000000];

    fgets(t,50000,stdin);
    fgets(s,50000,stdin);

    printf("%c",t[1]);


}

但是,单个 fgets 不会。

#include <stdio.h>
#include <string.h>
#include <math.h>

int main()
{
    char t[5000000];
    char s[5000000];

    fgets(t,50000,stdin);

    printf("%c",t[1]);

}

其他帖子讨论了一些返回和“/n”问题,但我不明白问题到底是什么。

【问题讨论】:

  • ts改成static char[]看看是否栈溢出
  • @timrau 这是堆栈溢出
  • 是的,就是这样,谢谢!!你能解释一下为什么会解决它吗?

标签: c arrays string segmentation-fault fgets


【解决方案1】:

数组太大而无法在堆栈上声明它们,它会填满并发生堆栈溢出,要么使用malloc 在堆上声明它们,要么将它们变小。

将它们声明为static 也会使其工作,因为静态变量存储在内存中的不同位置而不是堆栈上。

【讨论】:

    【解决方案2】:

    仅供参考:

    堆栈大小因平台而异,在 linux 平台上堆栈大小默认为 8MB。您可以使用系统调用 getrlimit() 和 setrlimit() 对其进行更改,也可以根据需要进行更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-19
      • 2013-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多