我无法分配堆栈变量 - 8086 程序集



我尝试编写一个获取字符串并在堆栈上复制它的过程。

这是我的代码:

cpyStr proc
    mov bp, sp    
;   save the IP
    mov bx, sp
;   copy the counter loop
    mov cx, [bp+4]
;   make local variable - need 30 bytes
    sub sp, [bp+4] * 2; length is byte so duplicate for word ...
;   copy the string's offset
    mov si, [bp+2] ; offset to si
copy:
    sub bx, 2 ; next word
    mov ax, [si] ; store the character in ax
    mov [bp], ax ; copy to stack's currect word
;   to the next .. 
    add si, 1 ; go to next character
loop copy
;   print
    push bx ; send local string var as parameter for printStr
    call printStr 
;   return the IP
    push    bx
;   returtn to main ....
    ret 4 ; delete 2 parameters 
endp ; end

主要:

start:
    mov ax,@DATA
    mov ds,ax
; print
    push strSize
    push offset string
    call cpyStr
; msg
    push offset passed
    call printStr
; end
    mov ah,4ch
    mov al,0
    int 21H
end start

数据段:

string  db "Heello$"
strSize dw  8
passed  db "Passed$"

由于某种原因,它无法成功处理。

你至少有三个问题。

首先,复制首先写入 [bp],覆盖函数的返回地址。堆栈缓冲区从 [sp] 开始。其次,向前遍历源缓冲区,向后遍历目标缓冲区,从而反转字符串。第三,在目标缓冲区中跳转 2 个字节,但在源缓冲区中仅跳转 1 个字节。正确的代码应该或多或少看起来像这样

    cpyStr proc
    mov bp, sp
    mov cx, [bp+4]
    sub sp, cx
    add cx, 1
    shr cx, 1
    mov si, [bp+2]
    mov bx, sp
copy:
    mov ax, [si]
    mov [bx], ax
    add bx, 2
    add si, 2
    loop copy
    push sp
    call printStr
    mov sp, bp

不应该是:数据细分受众群中的string db "Hello", $以及passed db "Passed", $

代码不应该是:

loop copy
mov sp, bx
pop sp           ;pop instead of push
call printStr
ret 4
endp