在没有写操作的情况下,内存值在运行时发生变化

Memory value changes during runtime without a write operation

我正在使用 NASM 在 SASM IDE 中编写以下程序。我有一个变量 m,它没有被改变,只读(现在)。在 div 操作之后,m 似乎从 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

问题是您已将所有变量声明为 words(16 位),但您继续读写 32 位寄存器 from/to。

您需要:

  1. 将您的变量声明从 DW 更改为 DD(双字)。
  2. 访问变量时使用 16 位寄存器,如 axbxcx 等。

您还可以将 16 位值扩展为 32 位,例如movsx ebx,word [m]。但这仅在从内存中读取时才有意义。