Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Screenshot when I am trying to create an array of length 10^5

Screenshot when I am trying to create an array of length 10^6

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 global instead or created it dynamically on the heap as

int* 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.

like image 945
Vikesh Avatar asked Sep 24 '11 19:09

Vikesh


2 Answers

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.

like image 112
Ernest Friedman-Hill Avatar answered Oct 04 '22 15:10

Ernest Friedman-Hill


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);
like image 38
Mysticial Avatar answered Oct 04 '22 17:10

Mysticial