[英]local array variable exc bad acces segmentation & local or global?
Hello I have seen this Maximum size of local array variable but I want to know why that's ok if the array is set ion global and not ok if it comes after the main. 您好,我已经看到了本地数组变量的最大大小,但是我想知道为什么如果将数组设置为离子全局而不是正常的(如果它位于主数组之后)是不可行的。
And another question in relation : Is it a good practice to have big memory objects that are defined in a.cpp and declared in a.hpp with extern ? 还有一个相关的问题:在a.cpp中定义并使用extern在a.hpp中声明的大内存对象是一种好习惯吗? Or better working with big memory defined in local fonction but defined as vector or new or malloc and passing them in fonction arguments. 或者更好地使用在本地函数中定义但定义为vector或new或malloc的大内存,并在函数参数中传递它们。
It's see my experience that are those questions i have to resolve... 看到我的经验就是那些我必须解决的问题...
Thank You 谢谢
#include <iostream>
using namespace std;
#define N (10000000000000)
int sd[N];
int main() {
// int sd[N];
return 0;
}
Declared at global scope: 在全球范围内声明:
int sd[N];
int main() {
return 0;
}
And the resulting binary just gets real big. 结果得到的二进制文件实际上变得很大。 When the process is loaded into memory, the entire set of global memory data is mapped in. 当进程加载到内存中时,将映射整个全局内存数据集。
Declared within a function: 在函数内声明:
int main() {
int sd[N];
return 0;
}
And the memory is allocated as soon as the function as invoked - and it's allocated from the stack . 并且一旦函数调用就分配内存-并且它是从堆栈分配的 。 The stack memory for a thread is usually initialized low, closer to a megabyte or less. 线程的堆栈内存通常初始化为低,接近兆字节或更小。 Once the stack memory runs out, it's game over. 一旦堆栈内存用完,游戏就结束了。
As others have pointed out in the comments, the right way to allocate a LARGE array is dynamically, using heap memory, which is typically plentiful. 正如其他人在评论中指出的那样,分配堆大型数组的正确方法是动态地使用堆内存,这通常很丰富。
int main() {
int* sd = new int[N];
...
delete [] sd; // free the allocated memory
return 0;
}
Even better, so you don't have to remember the delete: 更好的是,因此您不必记住删除操作:
int main() {
std::vector<int> sd(N);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.