Matan
Matan

Reputation: 179

Assembly Code doesn't Work with Stack Correctly

I'm practicing Assembly and I encountered a problem with it. Here is my code (Assembly 8086):

org 100h

.model small
.stack 100h

.data
    arr db 2, 2, 3, 4, 5
    len equ $-arr
    sum db 0 
    
.code

jmp _start

Sum1 proc
    push bp
    mov bp, sp
    
    mov bx, [bp+6]    
    xor ax, ax         
    
    mov cx, len        
    cmp cx, 0          
    je _end
    
LoopSum:
    mov di, cx         
    add al, [bx+di-1]  
    loop LoopSum

_end:
    mov [bp+4], al     
    pop bp
    ret
Sum1 endp

_start proc
    mov ax, @data
    mov ds, ax
    
    push offset arr
    push offset sum
    call Sum1
    
    mov ax, 4c00h
    int 21h
    ret
_start endp
end

My problem is that the variable sum (represented by bp+4) has a wrong value (0 instead of 10 as expected). Did I miss something?ㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤㅤ

Upvotes: 1

Views: 83

Answers (1)

L-S
L-S

Reputation: 189

  1. use [bp+4] (instead of [bp+8])

  2. add another register so you will be able to access it like this: [[bp+4]] (but that's not actually valid syntax; x86 doesn't have double-indirection in one addressing mode. That's why you need another register to load the pointer into.)

    You should change your _end block to this one:

_end: 
    mov si, [bp+4]
    mov [si], al     
    pop bp
    ret

Upvotes: 5

Related Questions