为什么大型本地数组会导致我的程序崩溃,而全局数组不会? [英] Why does a large local array crash my program, but a global one doesn't?

查看:31
本文介绍了为什么大型本地数组会导致我的程序崩溃,而全局数组不会?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有大型全局数组的程序:

Program with large global array:

int ar[2000000];

int main()
{
}

具有大型本地数组的程序:

Program with large local array:

int main()
{
    int ar[2000000];
}

当我在主函数中声明一个大数组时,程序崩溃并显示SIGSEGV(分段错误)".

When I declare an array with large size in the main function, the program crashes with "SIGSEGV (Segmentation fault)".

但是,当我将其声明为全局时,一切正常.这是为什么?

However, when I declare it as global, everything works fine. Why is that?

推荐答案

全局声明数组会导致编译器在已编译二进制文件的数据部分中包含数组空间.在这种情况下,您将二进制大小增加了 8 MB(每个 int 2000000 * 4 个字节).但是,这确实意味着内存始终可用,不需要在堆栈或堆上分配.

Declaring the array globally causes the compiler to include the space for the array in the data section of the compiled binary. In this case you have increased the binary size by 8 MB (2000000 * 4 bytes per int). However, this does mean that the memory is available at all times and does not need to be allocated on the stack or heap.

@Blue Moon 正确地指出 未初始化 数组很可能会分配在 bss 数据段中,实际上可能不占用额外的磁盘空间.初始化数组将被静态分配.

@Blue Moon rightly points out that an uninitialized array will most likely be allocated in the bss data segment and may, in fact, take up no additional disk space. An initialized array will be allocated statically.

当您在程序中声明一个如此大的数组时,您可能已经超出了程序的堆栈大小(并且具有讽刺意味的是导致了堆栈溢出).

When you declare an array that large in your program you have probably exceeded the stack size of the program (and ironically caused a stack overflow).

动态分配大数组的更好方法是使用指针并在堆上分配内存,如下所示:

A better way to allocate a large array dynamically is to use a pointer and allocate the memory on the heap like this:

using namespace std;
int main() {
  int *ar;
  ar = malloc(2000000 * sizeof(int));

  if (ar != null) {
    // Do something 
    free(ar);
  }

  return 0;
}

关于C 程序的内存布局的一个很好的教程可以在这里找到.

这篇关于为什么大型本地数组会导致我的程序崩溃,而全局数组不会?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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