C - 巨大数组 - 段错误(核心转储)

标签 c arrays

我收到错误“段错误(核心已转储)

如果循环数 = 207500 或更小,这两种方法都有效。但是,如果我增加此值(例如 2100000),我会收到错误

#include <stdlib.h>

void main()
{
  long i;
  long loops;

  loops = 2075000; // works
  loops = 2100000; // Segmentation fault (core dumped)

  if (1) {       
    int arr[loops]; // stack array
    for (i = 0; i < loops; i++) {
      arr[i] = 3;
    }
  }

  if (1) {
    int *arr = (int *) malloc(sizeof(int) * loops); // heap array
    for (i = 0; i < loops; i++) {
      arr[i] = 3;
    }
  }

}

我通过分配了 8GB RAM 的 Virtual Box 使用 Ubuntu 12.04 LTS

最佳答案

堆栈溢出,与堆相比,堆栈空间非常有限。您可以找到列出的典型堆栈大小 Stack Overflow Problems article :

platform    default size       
=====================================
SunOS/Solaris  8172K bytes
Linux          8172K bytes
Windows        1024K bytes
cygwin         2048K bytes 

另一种方法是通过 malloc 动态分配数组,这将使用更丰富的堆。

关于C - 巨大数组 - 段错误(核心转储),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22522769/

相关文章:

Javascript 重写之前的值?

javascript - 使用 Javascript 在数组数组中搜索第一个索引

关于不可移植项​​目的 C 标准未定义行为

c - 如何优雅地退出 X11 事件循环?

c - 在 C 中使用带有 unicode 字符串的正则表达式

ruby - 为什么 array.slice 对 (length, n) 的行为不同

使用其他宏作为参数调用 C 宏

c - 当我将 std=c99 标志添加到 gcc 时,fileno、F_LOCK 和 F_ULOCK 变得未声明和不可用

arrays - Int 的 Swift 3 二维数组

javascript - Javascript将字符串转换为多维数组