运行期间内存值在没有写入操作的情况下更改

时间:2015-09-28 05:59:49

标签: assembly nasm

我正在使用NASM在SASM IDE中编写以下程序。我有一个变量m,它只是不被改变只读(现在)。不知何故,在div操作之后,它看起来像是从6变为983046。

这是完整的.asm代码:

; TO COMPILE:
; nasm -f elf -g -F stabs lab.asm -l lab.lst
; gcc -m32 lab.o -o lab

global main
extern printf

SECTION .data

m DW 6 ; Number being check for perf median
t DW 0 ; Sum of preceeding numbers
n DW 0 ; Sum of suceeding numbers
d DW 0.5

SECTION .text

main:
; Safe registers are EBX, EBP, ESI, EDI, and ESP.
; Formula to find 1-6 (including the number 6

push message
call printf
add esp, 4

mov ebx, [m]
; Test print variable
push ebx
push dataM ; Needed to format the value as "%d"
call printf
add esp, 8

; Calculate T
mov ebx, [m]
mov edi, [m]
dec ebx

imul ebx, edi
mov [t], ebx

mov ax, [t]
mov bl, 2
div bl


mov [t], ax ; Done Calculating t
mov ebx, [t] 

push ebx
push dataM2 ; Needed to format the value as "%d"
call printf
add esp, 8

; This Doesn't work?
mov ebx, [m] ; Value of m has seemingly changed??

push ebx
push dataM2 ; Needed to format the value as "%d"
call printf
add esp, 8



ret


message:
db "Lab_2 Start:", 10,0

dataM:
db "Testing: %d...", 10, 0

dataM2:
db "DEBUG: %d", 10, 0

输出:

Lab_2 Start:
Testing: 6...
DEBUG: 15
DEBUG: 983046

(预期)输出:

Lab_2 Start:
Testing: 6...
DEBUG: 15
DEBUG: 6

1 个答案:

答案 0 :(得分:2)

问题是你已经将所有变量声明为 words (16位),但是你继续从它们读取和写入32位寄存器。

您需要:

  1. 将变量声明从DW更改为DD(双字)。
  2. 访问变量时,请使用axbxcx等16位寄存器。
  3. 您还可以将16位值扩展为32位,例如movsx ebx,word [m]。但这只有从内存中读取时才有意义。