naive231 naive231 - 2 months ago 13x
C Question

What is the meaning of `movq` and `movw` in initializing array in C?

I have an initialization of array in C like that:

char buf[10]={0};

And I show its assembly code in gdb, it shows up:

char buf[10]={0};
0x0000000000400591 <+20>: movq $0x0,-0x20(%rbp)
0x0000000000400599 <+28>: movw $0x0,-0x18(%rbp)

I know the offset base on
is allocating space, but I don't know what is the meaning of
? Seems that it not allocate the space only, initialization also be done at the same time. But why the offset is 0x20 or 0x18?


These instructions do not allocate space. By the time they are executed the space (on the stack) is already allocated. All they do is initialize that space with zeros.

On your platform local variables are stored at negative offsets from rbp. Your array has 10 bytes in it and is stored at offset -0x20 from rbp. The

movq   $0x0,-0x20(%rbp)

instruction sets the first 8 bytes of buf to zero (a "quad word" - q in movq). The

movw   $0x0,-0x18(%rbp)

instruction sets the remaining 2 bytes of buf to zero (a "word" - w in movw).

Note that -0x20 + 8 is -0x18. That's where -0x18 came from.

      |----------------- buf -----------------|

    --+---+---+---+---+---+---+---+---+---+---+--     ---+---
...   | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |   ...    |   ...
    --+---+---+---+---+---+---+---+---+---+---+--     ---+---
      ^                               ^                  ^
      rbp - 0x20                      rbp - 0x18         rbp

                    zeroed              zeroed
                      by                  by 
      |------------- mowq ------------|--movw-|