为什么一个大本地阵列崩溃我的程序? [英] Why does a large local array crash my program?

查看:116
本文介绍了为什么一个大本地阵列崩溃我的程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计划与全球大数组:

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, but 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月亮正确地指出,一个的未初始化的阵列将最有可能在 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;
}

在href=\"http://www.geeksforgeeks.org/memory-layout-of-c-program/\"> C程序的内存布局可以在这里找到的

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

这篇关于为什么一个大本地阵列崩溃我的程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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