1

The following code, when compiled and run, gives me a segmentation fault. Why is this?

#include <stdio.h>
#include <limits.h>

int main(void)
{
  int fat_array[INT_MAX];

  return 0;
}
Uclydde
  • 1,414
  • 3
  • 16
  • 33
  • 1
    Your system, that time, did not have enough memory for a _local_ array that big. It tried and failed at run time. – chux - Reinstate Monica Nov 10 '18 at 22:22
  • 1
    stackoverflow without the .com – Petr Skocik Nov 10 '18 at 22:22
  • 2
    You'd need 8 GiB of stack space for `int fat_array[INT_MAX]`; Unix-like systems are generous and normally give you 8 _MiB_ of stack space; Windows is more conservative and normally only gives you 1 MiB. Either way, it's massively less space than needed. Either allocate the array at file scope (outside `main()`), or use dynamic memory allocation (`malloc()` et al). – Jonathan Leffler Nov 10 '18 at 22:25

1 Answers1

3

What you are requesting is to have about 2,147,483,647integer spaces allocated to you. Each integer is usually four bytes so that's 8,589,934,588 bytes which is 8 gigabytes of memory. This is likely above the allowed amount of memory a single process is allowed to reserve, and for good reason, so you get an error.

Mitch
  • 3,342
  • 2
  • 21
  • 31
  • 2
    It's slightly misleading to say "above the allowed amount of memory a single process is allowed to reserve". If it were to be heap allocted and the system has enough it's fine to use to reserve/allocate as much and there's no general limit for memory. The specific problem here is that it's "stack" allocated (aka automatic storage). – P.P Nov 10 '18 at 22:45