Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation fault and core dumped when trying to declare a big array [duplicate]

Tags:

arrays

c

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?

like image 408
james Avatar asked Nov 04 '13 22:11

james


People also ask

Why do I get segmentation fault core dumped?

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.

What causes segmentation fault core dumped in Python?

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.

What is segmentation fault in array?

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, ...


1 Answers

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;
like image 77
abelenky Avatar answered Sep 18 '22 00:09

abelenky