0

Possible Duplicate:
C programming, why does this large array declaration produce a segmentation fault?

Why does this program crash? It works fine for a max of 1e6, and works fine if I don't set every value to 0.

Doesn't the program get all of the memory allocated?

int main() {
    const int max = 10000000; // 1e7
    int end[max];
    unsigned int i;
    for ( i = 0; i < max; i++ )
        end[i] = 0;
}


$ gcc test.c && ./a.out 
Segmentation fault (core dumped)
Community
  • 1
  • 1
Andreas
  • 7,470
  • 10
  • 51
  • 73

3 Answers3

4

Variable-length arrays are usually allocated on the stack. Stack space is limited; you are probably getting a stack overflow here. You can't allocate a very large size like that on such memory location. Your array is too big to fit in your program's stack. A better idea to allocate such size is to allocate on the heap.

#include <stdlib.h>

int *end = malloc(sizeof *end * max);

/* some stuff */

free(end);

The heap is many times larger than the stack.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
md5
  • 23,373
  • 3
  • 44
  • 93
1

Your stack size is limited by your operating system.

If you have to allocate very big values, don't use the stack but use the heap with malloc().

Intrepidd
  • 19,772
  • 6
  • 55
  • 63
1

It probably is a stack size problem.

You could manually check and change your stack size with setrlimit and getrlimit

http://linux.die.net/man/2/setrlimit

You can also do it when compiling with the --stack option:

 gcc --stack,<your size> ...
imreal
  • 10,178
  • 2
  • 32
  • 48