0

The snippet below doesn't return 0 in VS2019 version 16.11.3. Why?

_text SEGMENT
;.486
;.model flat,stdcall
;.stack 4096

.code
main PROC
    mov al, 0
    add al, 5
    ret
main ENDP
_text ENDS
END

The console window is shown below:

enter image description here

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
João Afonso
  • 1,934
  • 13
  • 19
  • 1
    Why do you expect this to return 0? `main` in C or C++ programs returns an `int`, which would be in `eax` or `rax`. – 1201ProgramAlarm Oct 01 '21 at 21:00
  • I'm not set up to test this, but I suspect it's because you're only setting the low byte of eax, and leaving the other three bytes with whatever values they had when your program started. Try replacing `mov al, 0` with `mov eax, 0`. – Joe White Oct 01 '21 at 21:01
  • 2
    `-509669371` is `0xe19f1005`, so it does reflect the fact that your code set the low byte to 5 without touching the upper bytes of whatever garbage was in RAX. Use `xor eax,eax` to zero the full RAX. You could also see this with a debugger if you set a breakpoint here before `ret` executes. (Unlike POSIX systems, Windows apparently doesn't truncate process exit statuses to 8 bits.) Also, don't post pictures of text; I had to type that negative decimal number by hand instead of copy/pasting because you didn't. – Peter Cordes Oct 01 '21 at 21:23
  • @JoeWhite You nailed it. Could you tell me where this is documented in Intel's manuals or in MASM docs? – João Afonso Oct 01 '21 at 21:25
  • [Why do x86-64 instructions on 32-bit registers zero the upper part of the full 64-bit register?](https://stackoverflow.com/q/11177137) quotes the Intel manual re: partial register writes of 8, 16, or 32-bit width. – Peter Cordes Oct 01 '21 at 21:26
  • @PeterCordes Thanks for the two comments above. – João Afonso Oct 01 '21 at 21:27

0 Answers0