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,170
  • 9
  • 47
  • 69

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
  • 178,696
  • 16
  • 303
  • 427
md5
  • 22,897
  • 3
  • 42
  • 92
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
  • 18,310
  • 5
  • 54
  • 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
  • 9,958
  • 2
  • 31
  • 46