Why do books say, “the compiler allocates space for variables in memory”?

前端 未结 7 1596
我在风中等你
我在风中等你 2020-12-31 10:54

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

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 11:35

    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)
    

提交回复
热议问题