In my C program, when I try to assign this array value:
double sample[200000][2];
I get a segmentation fault error. But when I use:
double sample[20000][2]
it works!! Is there a limit to these index values?
In my C program, when I try to assign this array value:
double sample[200000][2];
I get a segmentation fault error. But when I use:
double sample[20000][2]
it works!! Is there a limit to these index values?
It looks like you tried to reserve space for 200,000 x 2 = 400,000
double values, and each double
is 8 bytes, so you tried to reserve around 3.2 Megabytes.
Even though your machine likely has a couple Gigs of memory, stack space is limited per-process and per-thread and may well be limited to 1 or 2 megabytes. So you cannot allocate 3 megs, and you crash.
To fix this, you want to change to dynamic memory, using malloc
.
That will let you allocate from heap-space which is much more plentiful than stack-space.
To use malloc:
double (*sample) [200000];
s = malloc(sizeof(*sample) * 2);
sample[0][0] = 0.0;
sample[1][199999] = 9.9;
You are likely overflowing your stack, since that is a automatic variable in most modern implementation they will allocated on the stack which has limited size.
For example the stack size in visual studio defaults to 1MB
but is modifiable. There is a more complete list of typical stack sizes here:
SunOS/Solaris 8172K bytes
Linux 8172K bytes
Windows 1024K bytes
cygwin 2048K bytes
An alternative to allocating on the stack if you have a large amount of data is to use dynamic allocation via malloc. The C FAQ has a good reference on How can I dynamically allocate a multidimensional array?, modifying their two-dimensional example for double:
#include <stdlib.h>
double **array1 = malloc(nrows * sizeof(double *));
for(i = 0; i < nrows; i++)
array1[i] = malloc(ncolumns * sizeof(double));