Segmentation Fault on creating an array in C
I have recently migrated to a new laptop - HP dv6119tx (Intel Core i5, 4 GB RAM). It has Windows 7 Home Premium 64 bit installed.
I am trying to create an array of type int
of length 10^6 in C++ (Dev C++), which I used to create comfortably on my last laptop (32 bit Windows 7 Ultimate/Ubuntu Linux, 2GB RAM) and every other environment I have programmed on (It should take around 3.5 MB of RAM). But with the current setup, I am getting a "Segmentation Fault" error in Debug Mode.
SCREENSHOTS (EDIT) :
The first screenshot shows 10^5 working on the current setup and 10^6 not. I do not have a screenshot for 10^6 working on my last machine but I have used it many times.EDIT:
The program would work just fine if I declared the array as g开发者_Python百科lobal instead or created it dynamically on the heap asint* a = new int[MAX];
But what I fail to understand is that when the local array is taking a meager 3.5 MB of memory on the stack (and was working fine on a 2 GB machine), why should this issue surface with a 4GB machine? Is this a user stack space issue? Can it be increased manually?
EDIT 2:
I am particularly asking this question because I have submitted numerous solutions on SPOJ with 10^6 sized arrays created on the stack. With my current setup, I feel crippled not being able to do that. I prefer stack over heap whenever possible because it has no memory leak issues; and local variables over global variables because they are neat and do not mess up the namespace.A four megabyte stack is pretty big. The default size on Windows is 1MB. You need to use the /STACK
option to the linker to ask for a larger size.
Arrays created like that are stored on the stack. However, the stack has very limited size, therefore you are hitting a stackoverflow and a crash.
The way to do it is to allocate it on the heap:
int *a = (int*)malloc(MAX * sizeof(int));
// Do what you need to do.
// Free it when you're done using "a".
free(a);
Instead of malloc'ating memory you can specify your buffer as static
. E.g.:
static int a[MAX];
Advantage of this approach is that you need not to track your memory allocation.
精彩评论