I have learnt that memory for global variables are allocated at program startup whereas memory for local variables are allocated whenever function call is made.
Case 1:
I have declared a global integer array of size 63500000 and memory used is 256 MB
Ideone Link
include <stdio.h>
int a[63500000];
int main()
{
printf ("This code requires about 250 MB memory\n");
return 0;
}
Case 2:
I have declared a local integer array of same size in main() and memory used is 1.6 MB
Ideone link
#include <stdio.h>
int main()
{
int a[63500000]= {1,5,0};
printf ("This code requires only 1.6 MB \n");
//printf ("%d\n", a[0]);
return 0;
}
Case 3:
I have declared a local integer array of same size in another function and memory used is 1.6 MB
Ideone Link
#include <stdio.h>
void f()
{
int a[63500000];
}
int main()
{
f();
return 0;
}
Please explain why there is difference in memory used or my concept of memory allocation is wrong ??
First of all: the ideone compiler is GCC.
So, what does GCC do when you compile this?:
gcc -S -O2 foo.cgenerates:i.e. nothing is allocated on the stack, at all.
The array is simply optimized away by GCC because it is never used.
GCC won’t do this with a global, because it is possible that a global is used in another compilation unit, and so it isn’t sure that it is never used. Also: The global is not on the stack (since it is a global).
Now, lets see what happens when you actually use the local array:
Things are very different:
This line:
subl $254000000, %espcorresponds to the size of the array. i.e. memory is allocated on the stack.Now, what if I tried to use the
barfunction in a program:We already saw, that the
barfunction allocates 250 or so megabytes on the stack. On my default GNU/Linux install, the stack size is limited to 8MB. So when the program runs, it causes a “Segmentation fault”. I can increase it if I want, by executing the following in a shell:Then I can run the program, and it will indeed run.
The reason why it fails on the ideone website is that they have limited the stack size when executing programs (and they should, otherwise malicious users could mess up their system).