Segmentation Fault When Using Variable To Initiate Array

无人久伴 提交于 2019-12-14 03:49:19

问题


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?


回答1:


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.




回答2:


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?



  • 回答3:


    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



    来源:https://stackoverflow.com/questions/7987672/segmentation-fault-when-using-variable-to-initiate-array

    易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
    该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!