3

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?

Taylor Price
  • 622
  • 1
  • 8
  • 21
user1026561
  • 81
  • 1
  • 3

3 Answers3

6

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.

Mysticial
  • 464,885
  • 45
  • 335
  • 332
0

There are two things that I see here:

  • As @Mysticial suggest, use malloc() to dynamically allocate your array. The code would look something like the following:
  • double *correlationData = (double *) malloc (arrayLength * sizeof(double));
    

  • Why is correlationData a global? Can you create it in your main() and pass it around?
  • Taylor Price
    • 622
    • 1
    • 8
    • 21
    0

    It is not valid to create a static array at run-time. When you pass in the large constant value then the array is created properly, which is why it works in that case.

    If you do not know the size of the array that you need to create at build time then you need to use malloc to allocate the memory. i.e.

    correlationData = malloc(arrayLength * sizeof(double));
    

    Small stacks is an issue for embedded devices / old OS's. If a linux process running on a desktop with several GB of free memory needs more stack space the kernel will provide it until it runs out of system memory. Although it's bad practice to grow the stack to very large levels

    John Beckett
    • 126
    • 2