Home > Back-end >  Adding another word in .data is messing up with values in x86
Adding another word in .data is messing up with values in x86

Time:07-05

I created a simple code to make a summation (currently the first 20 numbers). Everything goes fine, even the functions I made to print a number. There's a single problem: I can't use both words I allocated at .data.

section .data 
    total dw 0
    index dw 1

If I add index to .data, the value of [total] goes from 0 to 65536. index's is still 1, and I don't have any clue of why this is happening.

I removed the loops and instructions in _sum20 to shorten the pasted code (I tested it).

section .data 
    total dw 0
    index dw 1

_start:
    call _sum20         
    call _printInt     
    end                 

_sum20:
    mov rax, [total] ; rax = 65536
    ret 

In the code above, [total] has a value of 65536

section .data 
    total dw 0


_start:
    call _sum20         
    call _printInt     
    end                 

_sum20:
    mov rax, [total] ; rax = 0
    ret 

Here, [total]'s value is 0

CodePudding user response:

The problem is simple: you defined total and data to be words, i.e. 2 byte quantities but then accessed the variables using quad word, i.e. 8 byte operations. This oversized memory access causes not just one variable, but also some unrelated memory after it to be affected.

To fix this problem, either change total and data to be quad word variables using the dq instead of dw directive, or change your code to access these variables with a 16 bit data size. For example, in your case you could do:

movzx rax, word [total]
  • Related