2

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.

6 Answers 6

6

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;
Sign up to request clarification or add additional context in comments.

1 Comment

What makes you think it's 70 megabytes? It doesn't say that an int is 32 bits in the C/C++ standard.
3

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

Comments

1

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.

2 Comments

76.2939453 megabytes in fact.
76.2939453 mebibytes (MiB), but 80 megabytes (MB).
1

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

Comments

0

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.