C:这取决于大小的数组初始化段错误,​​并调用printf() [英] C: Array initialization segfaults depending on size and call to printf()

查看:118
本文介绍了C:这取决于大小的数组初始化段错误,​​并调用printf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另外一个学生问我有什么可能是错误的,他C $ C $℃。我成功地再现了错误的行为,并在完全不知道为什么出现segfaults。考虑这个微型C PROGRAMM:

Another student asked me what could be wrong with his C code. I successfully reproduced the erroneous behavior and have completely no idea why this segfaults. Consider this tiny C programm:

#include <stdio.h>

int main(void) {
    int N = 590;
    double A[N][N];
    double B[N][N];
    double C[N][N];
    printf("done");
}


  • 设置 N 来的值​​&LT; = 590:结果
    这将运行没有错误,有或没有输出。

  • 设置 N 来的值​​> 590:

    • 运行flawlessy与输出线拆除。

    • 编译和运行输出:分段故障

      • Set N to a value <= 590:
        This runs without errors, with or without output.
      • set N to a value > 590:
        • Runs flawlessy with output line removed.
        • Compile and run with output: segmentation fault
        • 什么是这个原因?有人能解释一下吗?

          What's the reason for this? Can anybody explain?

          推荐答案

          您尝试比它的可导致在栈上分配更多的内存的堆栈溢出。通常它是更好的动态使用分配巨大数组一样,的malloc 释放calloc realloc的。不要忘记调用免费来释放此内存,当你用它完成:)

          You try to allocate more memory than it's available on the stack which causes stack overflow. Usually it is much better to allocate huge arrays like that dynamically by using malloc, calloc or realloc. Don't forget to free this memory by calling free when you finish with it :)

          这些问题将有助于你太:结果
          C / C ++程序结果的最大堆栈大小
          段错误就用C 结果创建数组
          段错误使用变量何时启动阵列

          These questions will help you too:
          C/C++ maximum stack size of program
          Segmentation Fault on creating an array in C
          Segmentation Fault When Using Variable To Initiate Array

          这篇关于C:这取决于大小的数组初始化段错误,​​并调用printf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆