Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Segfault while allocating staticaly an int array

Tags:

c

malloc

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.

like image 679
Gaël Barbin Avatar asked Jan 17 '23 01:01

Gaël Barbin


2 Answers

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 :)

like image 91
Levon Avatar answered Jan 28 '23 01:01

Levon


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:

  1. There is no mechanism for them to report allocation failure, other than to crash or cause some other undefined behaviour.

  2. 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!

like image 29
Oliver Charlesworth Avatar answered Jan 28 '23 00:01

Oliver Charlesworth