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 :)
Assuming length
is not a constant, then the first form is a variable-length array (VLA), and you have just encountered one of their biggest problems.
Best practice is to avoid VLAs for "large" arrays, and use malloc
instead, for two reasons:
There is no mechanism for them to report allocation failure, other than to crash or cause some other undefined behaviour.
VLAs are typically allocated on the stack, which is typically relatively limited in size. So the chance of it failing to allocate is much higher!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With