0

When n is a big number, say 10^7

  unsigned n, m;
  scanf("%u %u", &n, &m);
  
  long arr[n + 1];
  // long *arr = malloc((n + 1) * sizeof(*arr));
  for (size_t i = 1; i <= n; ++i)
    arr[i] = 0;

I get segmentation fault when I declare arr as long arr[n + 1];, but it works fine when I change to use malloc() (with same number of space, as the marked code).

Why there's difference? I thought stack and heap share the same space, like the pic depicts.

enter image description here

trincot
  • 317,000
  • 35
  • 244
  • 286
Ca Chen
  • 63
  • 8
  • Most operating systems impose a fixed maximum limit on the stack, usually a few megabytes or so, which you are well over. This is in order to cut off buggy programs that are infinitely recursing before they waste too much CPU and memory. The picture of stack and heap growing arbitrarily toward each other is simplistic and does not represent how modern operating systems do things. – Nate Eldredge Nov 11 '21 at 15:59
  • Does this answer your question? [Is there a limit for the total variables size on the stack?](https://stackoverflow.com/questions/2050207/is-there-a-limit-for-the-total-variables-size-on-the-stack) – Nate Eldredge Nov 11 '21 at 16:30
  • @NateEldredge I understand there's a limit on stack, but what about heap? – Ca Chen Nov 12 '21 at 06:20
  • Usually for "heap" (dynamic allocation via `malloc` and similar), the only limit is the total amount of available memory on the system. The user or system administrator may be able to configure a lower limit, but even so it would normally be much more than a few megabytes. – Nate Eldredge Nov 12 '21 at 14:49
  • @NateEldredge does it means that the full space of stack will always smaller than heap, though the diagram above shows they share the same space. – Ca Chen Nov 13 '21 at 04:03

0 Answers0