Search code examples
assemblymemory-managementx86nasmcpu-registers

Nasm - move value from a 4 byte register into an 1 byte address space


How does nasm behave when I move the 4 byte value stored in eax, ebx, ecx etc. to an address space that has less than 4 bytes of space allocated? Respectively how does nasm behave when I move a 1 byte value stored in var to an 4 byte register?

Like:

.bss
var resb 1
.text
mov eax, 2000000000
mov [var], eax

xor ebx, ebx
mov ebx, [var]

What values would [var] and ebx have? And why? When calling printf with %d I get 2000000000 as a result. But how can this be? var can only save 1 byte. How is it possible that a number that requires a larger amount of bytes can be received from it?


Solution

  • Unlike MASM, NASM doesn’t track the size of variables. (It doesn’t actually have variables, it just has labels.)

    So the mov instruction from/to a 4-byte register will simply overwrite (or read) whatever is in the four bytes starting at the label var.

    NASM doesn't stop you from writing buggy code; assembly language doesn't have variables or types; it's up to you to use instructions that make sense for your memory layout.

    To do a narrow store: mov [var], al

    To do a narrow load (into a full register): movzx ebx, byte [var]