4

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.

Gaël Barbin
  • 3,769
  • 3
  • 25
  • 52

3 Answers3

5

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

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
3

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!

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
1

implied auto considered harmful

To concur with the answers already given, if the faulting code had been written with an explicit storage class, this common problem might be more obvious.

void
not_enough_stack(void)
{
    auto int on_stack[2560 * 1000];
    printf("sizeof(stack) %d\n", sizeof(on_stack));
}
msw
  • 42,753
  • 9
  • 87
  • 112