3

I get a segfault from this line of code:

int fatblob[1820][286][5];

Why is that?

Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • 2
    possible duplicate of [Getting a stack overflow exception when declaring a large array](http://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array) – Michael Mrozek Jun 29 '10 at 20:09
  • possible duplicate of [Create a big array in C++](http://stackoverflow.com/questions/3137598/create-a-big-array-in-c) – bk1e Jun 30 '10 at 04:57
  • Possible duplicate of [Getting a stack overflow exception when declaring a large array](https://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array) – hat May 30 '18 at 16:03
  • Possible duplicate of [Segmentation fault on large array sizes](https://stackoverflow.com/questions/1847789/segmentation-fault-on-large-array-sizes) – phuclv Sep 02 '19 at 01:28

5 Answers5

8

Because your stack segment is smaller then 1820*285*5 ints. It's usually in a neighborhood of 1MB.

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
7

You're trying to allocate 1820 * 285 * 5 * sizeof(int) bytes = about 10MB (if sizeof(int) == 4). That's probably more bytes than your OS gives you for stack allocation by default, so you get a stack overflow/segfault.

You can fix this by either asking for extra stack when you create the thread, allocating on the heap, or changing the OS defaults.

JSBձոգչ
  • 40,684
  • 18
  • 101
  • 169
3

Because stack overflows. Try to allocate that array on the heap.

3
int fatblob[1820][286][5];

you are trying to allocate a memory location of 180*286*5*4 (let size of int = 4) that is around 9.8 MB, so there is a possibility of having lesser default stack size on your OS.

LINUX has 8192 KB(i.e. 8 MB) of stack size. So obviously you will be getting a stack overflow if you are trying to allocate more memory on stack.

You can try changing the stack size of your OS. In LINUX you can try ulimit

ulimit -s < whateversize you want it to be>

like

$ ulimit -s 1024

I hope it will help you.

Kumar Alok
  • 2,512
  • 8
  • 26
  • 36
1

Automatic variables (the default type) in C are usually allocated on the stack. The stack is a memory region allocated per thread, and while it may grow on many operating systems, it always has a limited size. danben's answer covers the default stack pretty well, but if you're using threads, you're allocating new ones in thread creation (e.g. pthread_attr_setstacksize). In general, large allocations are better done on the heap (malloc/new), but even that may be too small sometimes. mmap() or similar sometimes help then.

Where did danben's answer go? It linked to some information on stack limits.

Community
  • 1
  • 1
Yann Vernier
  • 15,414
  • 2
  • 28
  • 26