0
#define N 10000000
int arr[N];

int main(void)
{
   int i;
   for(i=0;i<N;i++)
      arr[i]=i+1;
}

Why declaring the array globally do not give any compilation error? What is the chance of the availability of contiguous memory of N*4 bytes in the stack? Same for declaring the array with static keyword.

STF
  • 1,485
  • 3
  • 19
  • 36

2 Answers2

2

Global, static global, and static variables do not need to be put in the stack. The stack is for variables who temporarily exists, and who are relative to a function call, the exact opposite of static/global variables who exist as a single and always present in memory entity.

Also, because that is stated in the C specifications, static and/or global variables have a default initialization to zeros. As most (if not all) compilers do not put them in the stack this cost nothing in term of program execution time.

jdarthenay
  • 3,062
  • 1
  • 15
  • 20
  • "because they are not in the stack" – I'd rather say "because that is stated in the C specifications" (see http://stackoverflow.com/a/8138702/2564301 for a quote). "The stack", on the other hand, is *not* part of the C specifications: http://stackoverflow.com/a/79936/2564301 (second comment). – Jongware Mar 28 '16 at 12:47
  • @Rad Lexus Is that better sir? – jdarthenay Mar 28 '16 at 13:00
2

enter image description here

This image should help. You can see that on the stack we are allocating memory only for local variables and arrays and function calls and pointers. While the Global variables/ Static are stored on Perm Storage.

Ajinkya Patil
  • 741
  • 1
  • 6
  • 17
  • A "normally" would be nice somewhere in your post. Actually, all of this is up to the compiler/linker and not specified anywhere. The C specs just put *requirements* on the storage, not where it needs to be. I have a compiler somewhere that puts global variables to the very bottom of the stack (i.e upwards the stack frame of `main`). – tofro Mar 28 '16 at 12:55