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

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

问题描述

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

int ar[2000000];

int main()
{
}

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

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

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

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

解决方案

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

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

当您在程序中声明一个很大的数组时,您可能已经超出了程序的堆栈大小(讽刺地导致了 堆栈溢出 ).

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

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

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

  return 0;
}

有关 C程序的内存布局的好指南,可以在这里找到./p>

Program with large global array:

int ar[2000000];

int main()
{
}

Program with large local array:

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

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?

解决方案

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.

EDIT: @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;
}

A good tutorial on the Memory Layout of C Programs can be found here.

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

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