Home > front end >  Increment a variable in nasm assembly
Increment a variable in nasm assembly

Time:06-27

I am making a OS in 32-bit protected mode assembly and need to increment (or decrement) a variable. My variable is defined like this:

Var: db 1

and I am trying to increment it like this:

mov ebx, [Var]
inc ebx
mov [Var], ebx

However, the variable is increased by a value WAY bigger then 1. Why is this happening and how do I fix it.

CodePudding user response:

Your problem is that you defined Var to be a byte-sized variable, but you operate on it as if it was a dword-sized variable. This causes you to read/write unrelated bytes around the variable, causing the strange numbers you observe.

To fix this, always operate on data with the correct data size. For example, do

movzx ebx, byte [Var]
inc ebx
mov [Var], bl

Note the asymmetry: we could have used mov bl, byte ptr [Var], but it's slow to write to partial registers (i.e. bl being a part of ebx). The instruction movzx makes sure to write the full register while only fetching a single byte from memory.

Or even simpler

inc byte [Var]
  • Related