Home > database >  (ASSEMBLY NASM x64 linux) how to move values to variables defined in data section?
(ASSEMBLY NASM x64 linux) how to move values to variables defined in data section?

Time:11-16

I'm trying to move a value to a variable in the data session but when I do it in mov [valor], rax I get invalid characters instead of a number that was supposed to be the subtraction of the current value of the variable minus 1.

    section .text
    global main,_start
main:
    mov ebp, esp
_start:

;read int value
mov edx,4
mov ecx,valor
mov ebx,1
mov eax,3
int 0x80

;write int value
mov edx,4
mov ecx,valor
mov ebx,1
mov eax,4
int 0x80

;load variable in stack
mov rax,valor
push rax
;load number 1 in stack
mov rax,1
push rax

;subtraction (valor - 1)
pop rbx
pop rax
sub rax,rbx
mov [valor], rax 

;write again int value
mov edx,4
mov ecx,valor
mov ebx,1
mov eax,4
int 0x80

;exit
mov ebx,0
mov eax,1
int 0x80

    section .data
valor: dd "%d", 4

The output when i enter with number 2:

2       ;first print
�@     ;second print

I appreciate any help

CodePudding user response:

In NASM an instruction like mov rax,valor will load the address of the valor variable. You need its value, so write mov rax, [valor].
Normally before doing subtraction on an inputted number you would need to convert the inputted characters into their binary equivalent, but your input of "2" can get subtracted by 1 the way you are doing it now:

; input "2"
mov eax, [valor]
sub eax, 1
mov [valor], eax
; output "1"

You can of course use the stack like you were doing if that's for learning purposes...

    section .data
valor: dd "%d", 4

This "%d" serves no purpose! Writing valor: dd 0 makes more sense. Putting valor in the .bss section would make the most sense.

  • Related