简体   繁体   中英

C++ array declare issue

This code is giving 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 :DA 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, eg:

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.)

如果我没错,那就是400万

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM