user629034
user629034

Reputation: 669

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.

Upvotes: 2

Views: 321

Answers (6)

andrewdski
andrewdski

Reputation: 5515

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.

Upvotes: 0

Duc Tran
Duc Tran

Reputation: 6304

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

Upvotes: 0

ajcl
ajcl

Reputation: 381

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

Upvotes: 1

Kiril Kirov
Kiril Kirov

Reputation: 38173

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

Upvotes: 3

snoofkin
snoofkin

Reputation: 8895

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.

Upvotes: 1

Seth Carnegie
Seth Carnegie

Reputation: 75150

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;

Upvotes: 6

Related Questions