我的打印声明的汇编部分出现问题,我正在使用MASM x86,FLAT内存。当我尝试像这样运行时,它给了我错误的数字(期待试验0。总和是:0)等等。但它从试验0到1到3,7,15,51,63 ......所以它加倍+1。现在,如果我改变了行
add esp, 12
到
add esp, 8
它给了我正确的数字(由于我将三个东西推到堆栈上,这没有意义),但最后,在它返回之前,它出错并停止工作,显然是由于堆栈中的错误。我已经尝试在不同的位置添加4个堆栈指针无济于事,在不同的位置打印,但我只是丢了。
My C片段:
extern "C"
{
int __stdcall ASM_Test(int Assignment);
void __cdecl ASM_Printf(char *pFormat, ...);
}
void __cdecl ASM_Printf(char *pFormat, ...)
{
va_list vargset = NULL;
va_start(vargset, pFormat);
vprintf(pFormat, vargset);
return;
}
完整汇编代码:
.data
nTotalNumber dd ?
nFinalVal dd ?
pFirstLine db 'For Trial %d. The sum is: %d', 0ah, 0
CountOffset EQU 4
finalValOffset EQU 8
.code
; for (int i = 0; i < maxCount; i++)
Test_ASM@4 PROC PUBLIC
push ebp
mov ebp, esp
mov DWORD PTR[EBP - CountOffset], 0 ;Setting my i to 0
mov DWORD PTR[EBP - finalValOffset], 0 ;Setting my Sum to 0
top:
mov eax, [EBP + FirstOffset] ;moving the first supplied arg into eax
cmp [EBP - CountOffset], eax ;Compares i < maxCount
jge finish ;ends if i is = or above maxcount
;if sum < maxCount
mov eax, [EBP - finalValOffset] ;Storing my sum into eax
cmp eax, [EBP + FirstOffset] ;compaires sum and max count
jge finish ;jumps if its not below
mov eax, DWORD PTR[EBP - finalValOffset]
add eax, DWORD PTR[EBP - CountOffset] ;sum + i
mov DWORD PTR[EBP - finalValOffset], eax ;Storing the value back into sum
push eax ;Printing stuff
mov eax, DWORD PTR[EBP - CountOffset] ;
push eax ;
mov eax, OFFSET pFirstLine ;
push eax ;
call ASM_Printf ;
add esp, 12 ;End Printing Stuff
;Second compare is to see if we met the requirements and can end.
mov eax, [EBP - finalValOffset] ;Storing my sum into eax
cmp eax, [EBP + FirstOffset] ;compaires sum and max count
jge finish
inc DWORD PTR[EBP - CountOffset] ;i++
jmp top
finish:
mov eax, DWORD PTR[ebp - CountOffset] ;Getting output
pop ebp ;Cleaning up the stack
ret 4 ; pops the arg from the stack on return.
Test_ASM@4 ENDP
END