Stack/heap overflow when declaring a large array

后端 未结 2 752
予麋鹿
予麋鹿 2020-12-11 23:23

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.

相关标签:
2条回答
  • 2020-12-11 23:40

    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

    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.

    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.

    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];
    

    You declare it as:

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

    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.

    0 讨论(0)
  • 2020-12-11 23:50

    Are you declaring this on the stack perhaps? Objects that big have to be on the heap!

    0 讨论(0)
提交回复
热议问题