Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segmentation Fault When Using Variable To Initiate Array

This is my first question posting so sorry if I make make any faux pas'

Using C

In my program I create a global variable pointer

double *correlationData;

In main I create this local variable:

int arrayLength = 0;

in main I have an if statement inside a for loop which contains

arrayLength++;

after the for loop I initiate an array and assign it to the pointer

double correlationArray[arrayLength];
correlationData = correlationArray; 

but I get a "segmentation fault" at this part of the code and I can't figure out why. If I print out arrayLength it is 1900000. First I thought maybe this was too big for an array so I tried

correlationData = correlationArray[1900000];

and that worked without any errors. Why I am getting this error?

like image 572
user1026561 Avatar asked Apr 01 '26 17:04

user1026561


1 Answers

This is due to a stackoverflow. You are creating a massive array on the stack.

1900000 of doubles is ~15 MB. A typical stack is on the order of 1 MB.

What you need to do instead is to allocate it dynamically using malloc().

In your second test case:

correlationData = correlationArray[1900000];

That doesn't make the array. It's just a wild array access that (un)luckily didn't crash.

like image 160
Mysticial Avatar answered Apr 04 '26 05:04

Mysticial



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!