声明大数组时堆栈/堆溢出 [英] Stack/heap overflow when declaring a large array

查看:96
本文介绍了声明大数组时堆栈/堆溢出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图声明一个1024 x 1024的float数组,但刚刚弹出一个窗口,说project_name.exe已停止工作...带有调试或关闭程序的选项.以前,我成功声明了1000 by 2 int数组.我已经在Internet上搜索了可能的原因,他们说与内存有关的问题,确切地说是堆栈/堆溢出".他们说,对于浮点数的情况甚至更糟.

I was trying to declare a 1024 by 1024 float array but a window just popped up saying project_name.exe has stopped working... with options whether to debug or close program. Previously, I succeeded declaring 1000 by 2 int array. I've kind of searched the internet for possible cause, and they said its memory related issue, "stack/heap overflow" in exact. They said that it is even worse for the case of float.

我最多只需要5或6个小数位即可.

I only need up to 5 or 6 decimal places.

有什么建议或建议吗?我在python和matlab中都没有遇到这个问题.我正在使用Microsoft Visual Studio 2010.

Any advice or suggestion? I didn't face this issue in python nor in matlab. I am using Microsoft Visual Studio 2010.

推荐答案

您是否将此声明为函数或方法中的局部变量?如果是这样,这是经典的堆栈溢出.对于VS2010,请参见 http://msdn.microsoft.com/zh-CN /library/8cxs58a6%28v=vs.100%29.aspx

Are you declaring this as a local variable in a function or method? If so it's a classic stack overflow. For VS2010 see http://msdn.microsoft.com/en-us/library/8cxs58a6%28v=vs.100%29.aspx

保留值指定虚拟内存中的总堆栈分配.对于x86和x64机器,默认堆栈大小为1 MB.在Itanium芯片组上,默认大小为4 MB.

The reserve value specifies the total stack allocation in virtual memory. For x86 and x64 machines, the default stack size is 1 MB. On the Itanium chipset, the default size is 4 MB.

因此,一个1024x1024的float数组(假设每个float包含4个字节)的时钟频率高达4mb-您已经在此处通过默认的堆栈限制了.

So a 1024x1024 array of floats (assuming 4 bytes per float) clocks in at a whopping 4mb - you've sailed right through the default stack limit here.

请注意,即使您拥有Itanium,也无法使用所有这4mb-例如,参数也需要存储在堆栈中,请参见 http://www.csee.umbc.edu/~chang/cs313.s02/stack. shtml

Note that even if you do have an Itanium you're not going to be able to use all of that 4mb - parameters, for example, will also need to be stored on the stack, see http://www.csee.umbc.edu/~chang/cs313.s02/stack.shtml

现在,您可以只是增加堆栈大小,但是总有一天您将需要使用更大的数组,因此这是一场消耗战,您将无法取胜.要解决这个问题,最好先解决它.换句话说:

Now, you could just increase the stack size, but some day you're going to need to use a larger array, so that's a war of attrition you're not going to win. This is a problem that's best solved by making it go away; in other words instead of:

float stuff[1024 * 1024];

您将其声明为:

float *stuff = new float[1024 * 1024];
// do something interesting and useful with stuff
delete[] stuff;

现在,它不再位于堆栈中,而是分配到堆中.请注意,这与罗伯特·哈维(Robert Harvey)在回答中提到的堆不同.您没有/HEAP选项的限制.

Instead of being on the stack this will now be allocated on the heap. Note that this is not the same heap as that mentioned by Robert Harvey in his answer; you don't have the limitations of the /HEAP option here.

这篇关于声明大数组时堆栈/堆溢出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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