Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Incrament a variable in nasm assembly

I am making a OS in 32-bit protected mode assembly and need to incrament (or decrament) 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 happenng and how do I fix it. Best Regards, Markian.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading