Segfault when distributing a staticaly int array

If i do it

int wsIdx [length];

I have segFault

but if i do it

int *wsIdx; wsIdx = (int *)malloc(sizeof(int) * length ); 

no problems.

This problem only occurs with a high length of 2560000 during my tests. I have enough memory. Could you explain to me the differences between the two distribution methods and why the first does not work? Thanks.

+4
source share
3 answers

The first gets allocated in the "stack" (the area usually used for local variables), and the second gets allocated in the "heap" area for dynamically allocated memory.

You do not have enough stack space to allocate in the first place, your heap is big.

This discussion of SO can be useful: What and where are the stack and heap? .

When you allocate memory dynamically, you can always check the success or failure of allocation by examining the return value of malloc / calloc / etc .. unfortunately, such a mechanism does not exist for the memory allocation mechanism on the stack.

Also: you might like to read this in the context of this question, especially this part :)

+5
source

Assuming length not a constant, then the first form is a variable length array (VLA), and you just ran into one of your biggest problems.

It is best to avoid VLA for "large" arrays and use malloc instead for two reasons:

  • There is no mechanism for reporting a distribution denial other than a failure or some other undefined behavior.

  • VLAs are usually allocated in a stack, which is usually relatively limited in size. Thus, the probability that he will not be able to isolate is much higher!

+3
source

implied auto is considered harmful

To agree with the answers already received, if the error code was written with an explicit storage class, this general problem may be more obvious.

 void not_enough_stack(void) { auto int on_stack[2560 * 1000]; printf("sizeof(stack) %d\n", sizeof(on_stack)); } 
+1
source

All Articles