I have written following assembly code for adding 10 numbers.I am able to compile it and execute it but I am getting wrong result.
I just wanted to know how do I print the value of total on scree.
section .data
num1: dw 10, 20, 30, 40, 50, 10, 20, 30, 40, 50
total: dw 0
msg : db "sum=%d",10,0
section .text
extern _printf
global _main
_main:
push ebp
mov ebp,esp
mov ebx,num1 ;point bx to first number
mov ecx,10 ;load count of numbers in ecx
mov eax,0 ;initialize sum to zero
loop:
add eax,[ebx]
add ebx,2
sub ecx,1
jnz loop
mov [total],eax
push total
push msg
call _printf
pop ebp
mov esp,ebp
ret
solution
section .data
num1: dd 10, 20, 30, 40, 50, 10, 20, 30, 40, 50,300
total: dd 0
msg : dd "sum=%d",10,0
section .text
extern _printf
global _main
_main:
push ebp
mov ebp,esp
mov ebx,num1 ;point bx to first number
mov ecx,11 ;load count of numbers in ecx
mov eax,0 ;initialize sum to zero
loop:
add eax,[ebx]
add ebx,4
sub ecx,1
jnz loop
mov [total],eax
push dword [total]
push msg
call _printf
mov esp,ebp
pop ebp
ret
I see a couple of issues here. First, you’ve got
num1andtotaldeclared asdw.dwmay sound like it means “dword”, but it means “data word”. You want these to bedd– “data dword”… since that’s how you’re using them. (andadd ebx, 4not 2) If you really need to use word (16-bit) values in 32-bit code, it can be done, but is awkward.The second problem I see is that
push totalbefore yourcall _printfpushes the address oftotal. You want the “[contents]” of memory here, sopush dword [total]. (push msgis correct)After this, you probably want
add esp, 8(I like to write it asadd esp, 4 * 2– two parameters of 4 bytes each). It is possible to “defer” this stack cleanup –mov esp, ebpwill fix you up, but it needs to be done BEFORE thepop ebp!!!… there may be more…