-
Memory Allocation
In my lecture notes it says
Code:
double array[1000000]; //should take 8Mbytes
When in fact this does not make an executable of 8mb, this it tells me though it does not say why and i was not at the lecture for part of this topic.
Code:
double array[1000000] = {1.0, 2.0 ...}; // this makes the file ~8mb
Why doesnt this make the file larger?
-
Such are the hazards of missing out on bits of technical subjects...
> double array[1000000]; //should take 8Mbytes
Goes into the uninitialised data segment (called BSS in the Unix world). Although that sounds bad, C guarantees that bss is filled with zeros when the program starts
One good thing about the BSS segment is that it doesn't take up space in the program image. The program just contains a linker instruction which says "I want X bytes of BSS'. The program loader reads this, allocates it, zeros it and hands it over to your program.
> double array[1000000] = {1.0, 2.0 ...};
This goes into the initialised data segment. Since this is loaded at the same time as the program is loaded, it takes up space in the program image.
Notice how the 8MB shifts from the bss to the data segment when the array is initialised
Code:
+ cat hello.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double a[1000000]
#ifdef INIT
= { 1, 2 }
#endif
;
int main ( ) {
return 0;
}
+ gcc hello.c
+ size a.out
text data bss dec hex filename
604 256 8000032 8000892 7a157c a.out
+ ls -l a.out
-rwxrwxr-x 1 spc spc 11274 Jun 12 11:25 a.out
+ gcc -DINIT hello.c
+ size a.out
text data bss dec hex filename
604 8000276 4 8000884 7a1574 a.out
+ ls -l a.out
-rwxrwxr-x 1 spc spc 8011290 Jun 12 11:25 a.out
-
Thanks for that in-depth reply, Much clearer.