【问题标题】:Issue in declaring array globally and within the function of size 10^7 in C++ [duplicate]在 C++ 中全局声明数组并在大小为 10^7 的函数内出现问题 [重复]
【发布时间】:2021-05-11 05:50:44
【问题描述】:

在 C++ 中,当我在函数内声明一个大小为 10^7 的数组时。我无法这样做。但是,当我在全局范围内声明这个具有相同大小的数组时,一切都运行得非常好。我的意思是=> 假设我在函数中声明了数组

void ArrayReturn(){
  int N = 1e7+10;
  int arr[N]={0};      //When I try to output the content of this array
                       // there is a blank screen only.
  // Now I start performing seive
}

但是,在我全局声明 arr 的同时,输出正常

int arr[10000010];
void ArrayReturn(){
  //perform sieve
  //output which uses the content of this array, comes fine now.
}
So, I just wanna know whether this issue is because something related to memory assigned to a function over stack is limited, or is there something else that I am missing or don't know at all? 
Kindly explain.

    

【问题讨论】:

标签: c++


【解决方案1】:

这是因为在函数中声明的局部变量将分配在堆栈内存空间中。大多数普通规格的堆栈是每个进程1MB或8MB,不能容纳10^7个整数或浮点数。

相反,全局变量将分配在数据段中。数据段大小的限制足够大,可以全局分配10^7大小的数组。

关于各类变量的位置的更多解释,可以参考下面的url。

Where in memory are my variables stored in C?

【讨论】:

    【解决方案2】:

    是不是因为一些栈大小限制了内存消耗??

    是的,在大多数环境中,堆栈的限制非常小。您的 10^7 数组的大小乘以 sizeof(element) 大约为 10 MiB,这比大多数默认堆栈大小都要大。

    您可能会通过告诉您的操作系统、链接器或程序加载器来增加限制,但这是个坏主意。想想你将如何计算限制。你需要它更大,但到底有多大?如果一个函数调用另一个然后另一个呢?你在一个时间点有多少个数组?函数会递归吗?

    最好使用堆。这意味着动态分配内存。对于连续的数据块,最好使用std::vector。

    【讨论】:

      【解决方案3】:

      本地(例如;函数范围)和全局变量通常存储在进程(线程)堆栈上。您大小的数组(我假设为 10^7 字节)无法放入典型的堆栈中,即使它是唯一的东西(它不是)。典型的堆栈大小最大为 8 MiB,您的数组至少为 9 MiB。

      使用动态分配,例如; std::vector 用于封装的动态分配,如std::array,或者 C 样式的数组分配在堆栈上。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        • 2015-12-01
        • 1970-01-01
        • 2019-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多