What am I doing wrong?
While using Eclipse on a Mac (2GB RAM) I have encountered the following problem:
Whenever I try to create an array which exceeds 8384896 bytes, I get segmentation faults. The following program would execute:
#include <stdio.h>
main()
{
double x[1048112];
printf("sizeof(x) = %li", sizeof(x));
}
and the output would be (as expected):
sizeof(x) = 8384896
But increasing the number of elements in x or creating additional variables in main() would result in an unexecutable program and segfaults. It looks like I’m hitting some memory limit and I don’t understand why this is happening.
I’d be really grateful if anyone could explain this to me, or maybe provide some sort of solution to my problem.
This is a stack overflow due to excessively large stack variables.
If you really need to allocate something that large, you can do so on the heap using
malloc:Note that with this change,
sizeof(x)no longer returns the size of the array, it returns the size ofdouble *. If you need to know how large your array is, you’ll need to keep track of that on your own.And, just for completeness, when you are done with the data, you will need to call
free, otherwise you’ll have one heck of a memory leak: