3

I have a program that has to declare a huge integer array of the size 1000000 in C (using GNU GCC compiler). I tried to declare the array in two different ways.

The two possible codes are :

#include <stdio.h>
int arr[1000000];
int main()
{
  return 0; 
}

and

#include <stdio.h>
int main()
{
  int arr[1000000];
  return 0;
}

The latter version hangs during runtime. What could be the possible reason?

Thanks a lot!!!

pavium
  • 14,808
  • 4
  • 33
  • 50
niting
  • 2,384
  • 3
  • 19
  • 20

2 Answers2

9

The second version allocates on the stack, the size of which may be limited on your system for any given process. The first one allocates in the data segment of the process, the size of which isn't limited (at least for these orders of magnitude of allocation size)

From this SO answer you can learn how to check for the stack allocation limit for various platforms like Linux and Windows. If you're on Linux it's as simple as:

ulimit -a
Community
  • 1
  • 1
Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
  • You can typically bump up the stack size up a gcc compiler option if needed. You should be able to ask gcc to flag stack overflows during compilation. – Paul Dec 12 '09 at 06:18
  • @Paul Surely, because of separate compilation, most stack overflows can only possibly be flagged at link time? – Pascal Cuoq Dec 12 '09 at 11:22
  • @Pascal: only some... recursion makes it indeterministic - you never know before runtime how deep it goes – Eli Bendersky Dec 12 '09 at 13:39
2

Since you used the word static in the title, it is a wonder that it did not occur to actually declare the variable static.

int main()
{
  static int arr[1000000];
  return 0;
}

You could also use dynamic allocation.

Clifford
  • 88,407
  • 13
  • 85
  • 165