If I do this
int wsIdx[length];
I’ve a segFault
but if I do this
int *wsIdx;
wsIdx = (int *)malloc(sizeof(int) * length );
there’s no problem.
This problem appears only when length is high, 2560000 during my tests. I’ve widely enough memory. Could you explain me the differences between the two allocation method, and why the first does not work? Thank you.
The first one gets allocated on the “stack” (an area usually used for local variables), while the second one gets allocated on the “heap” an area for dynamically allocated memory.
You don’t have enough stack space to allocate in the first way, your heap is large.
This SO discussion might be helpful: What and where are the stack and heap?.
When you are allocating memory dynamically, you can always check for success or failure of the allocation by examining the return value of malloc/calloc/etc .. no such mechanism exists unfortunately for allocating memory on the stack.
Aside: You might enjoy reading this in the context of this question, especially this part 🙂