-1

I have an int flags[(1<<20)]; array and it seems that there's something wrong, and it causes segmentation fault. Is this a stack overflow problem? How much should I set stack size and how?

phuclv
  • 37,963
  • 15
  • 156
  • 475

2 Answers2

0

An int array of that size is 4MB. Depending on system, this number maybe large or not. In x86 Linux the default stack size is usually 8-10MB but on others this may vary

In Linux you can set the stack size (in KB) by the following command

ulimit -s 8192

but that will affect the stack size of all processes and is not recommended. To increase stack size of only your own process then use setrlimit

In Windows stack size is set at link time, but again, it should only be increased in necessary situation

Stack should only be used for small and medium size variables. For such large array you should allocate on heap instead

int *flags = malloc((1 << 20)*sizeof(int));

And remember to free it after using

phuclv
  • 37,963
  • 15
  • 156
  • 475
  • 1
    `int *flags = malloc((1<<20) * sizeof *flags);` – Keith Thompson Nov 06 '13 at 03:44
  • 2
    Note that `ulimit -s` changes the stack size limit for the main OpenMP thread only. The stack size for the other OpenMP threads is controlled by the `OMP_STACKSIZE` environment variable - see [here](http://stackoverflow.com/a/13266595/1374437). – Hristo Iliev Nov 06 '13 at 13:11
  • I tried both ulimit -s and OMP_STACKSIZE, up to 81920KB, it's still not working... Just two int[(1<<20)] array – user2958667 Nov 07 '13 at 11:49
  • Did you try heap allocating? And where did the program stop or the fault appeared right at first? – phuclv Nov 07 '13 at 12:06
  • yeah I tried. The program stopped at first "Segmentation Fault" – user2958667 Nov 10 '13 at 01:52
0

If your programming language is C++, then use std::vector, but not C-style array:

std::vector<int> flags(1<<20);
flags[0] = 1;

If your programming language is C, then read answer of Lưu Vĩnh Phúc

SergV
  • 1,269
  • 8
  • 20