Why do books say, \"the compiler allocates space for variables in memory\". Isn\'t it the executable which does that? I mean, for example, if I write the following program
Of course compiler doesn't "allocate space for variables". Compiler generates a code which allocates space for variables in memory.
I.e. if you have
int foo;
foo = 1;
in source code, compiler may generate a code like
int* fooPtr = allocate sizeof(int)
*fooPtr = 1;
In the x86 architecture, usually that allocate
thing will be a single assembly instruction:
sub esp, 4 ; allocate 4 == sizeof(int) bytes on stack
; now the value of "esp" is equal to the address of "foo",
; i.e. it's "fooPtr"
mov [esp], 1 ; *fooPtr = 1
If you have more than one local variable, compiler will pack them into a structure and allocate them together:
int foo;
int bar;
bar = 1;
will be compiled as
struct Variables { int foo; int bar; };
Variables* v = allocate sizeof(Variables);
v->bar = 1;
or
sub esp, 4+4 ; allocate sizeof(Variables) on stack
mov [esp + 4], 1 ; where 4 is offsetof(Variables, bar)