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?
Core Dump/Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” When a piece of code tries to do read and write operation in a read only location in memory or freed block of memory, it is known as core dump. It is an error indicating memory corruption.
A segfault occurs when a reference to a variable falls outside the segment where that variable resides, or when a write is attempted to a location that is in a read-only segment.
A segmentation fault or access violation occurs when a program attempts to access a memory location that is not exist, or attempts to access a memory location in a way that is not allowed. /* "Array out of bounds" error valid indices for array foo are 0, 1, ...
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With