0

The following C function:

int main(void) {
    char name[10] = "H";
}

Produces the following (unoptimized) assembly in Compiler Explorer:

main:
        pushq   %rbp
        movq    %rsp, %rbp
        movq    $72, -10(%rbp)
        movw    $0, -2(%rbp) <--------- ??
        movl    $0, %eax
        popq    %rbp
        ret

What does the line above do? I would think we would want to null terminal the string by adding a $0 but I don't undertand why it's being added at -2. If helpful, here is a screenshot:

enter image description here

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • @JosephSible-ReinstateMonica I don't think so. It seems to be more related to alignment, as the offset is basically ARRAY_LEN % 8. – samuelbrody1249 Jan 08 '21 at 03:05
  • 1
    Hint: How many bytes long is your array? How many bytes are affected by the instruction you marked and the one immediately before it? – Joseph Sible-Reinstate Monica Jan 08 '21 at 03:06
  • Maybe you're mixed up on where exactly things are getting stored. `-2(%rbp)` and `-1(%rbp)` are the last 2 bytes of the 10-byte array. The first 8 of which were written by `movq`. – Peter Cordes Jan 08 '21 at 03:37
  • @PeterCordes ah, ok. So it adds in the first 8 bytes with the `movq` and then pads the last two with zero from the `movw $0`. Is that correct? – samuelbrody1249 Jan 08 '21 at 04:28

0 Answers0