开发者

C++ array declare issue

This code is givi开发者_C百科ng me segfault :

#include <stdio.h>  

int main(int argc,char** argv[]){  

int ar[20000000];  

return 0;  

}  

But if I reduce the size of array by 0 - then its fine. Am I exceeding the max size? What if I want to store that amount of integers? Thanks.


It probably has to do with the fact that you're trying to allocate over 70 megabytes of data on the stack. Windows has a default stack size of 1 megabyte per thread IIRC. Try allocating it on the free-store with new, like so:

int* ar = new int[20000000];

and when you're done using it, delete[] it:

delete[] ar;


You got stack overflow :D A real one.

Allocate the memory on the heap, using new

int* ar = new int[ 20000000 ];
// do stuff with ar
delete[] ar; // do **not** forget about this


the declaration of int ar[20000000] on the stack, takes appx 70MB+ (76.2939453MB) of memory... maybe you run out of space?

Use new to allocate on the heap.


You may be exceeding the size allowed by the stack frame, which is enforced by your compiler. If you were to allocate the space dynamically, e.g.:

int array = new int[SIZE]

you would be limited by your OS and hardware rather than your compiler. (This is because dynamically allocating memory stores it on the heap, whereas a locally declared variable is stored on the stack, which has a stricter size limitation.)


If i'm not wrong, 4 million is the limit


If you really want to allocate this array on the stack, you can. You just need to increase the stack size. You don't say what compiler / linker you are using, but instructions for Visual Studio C++ are here: http://msdn.microsoft.com/en-us/library/tdkhxaks.aspx and other environments should have similar options.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜