[英]Assembly Power(A,b) function
我正在嘗試根據以下C代碼制作匯編power(a,b)函數:
int power(int x, int y)
{
int z;
z = 1;
while (y > 0) {
if ((y % 2) == 1) {
y = y - 1;
z = z * x;
} else {
y = y / 2;
x = x * x;
}
}
return z;
}
盡管由於某種原因,它只能正確輸出某些輸出,但我無法弄清楚問題出在哪里。 這是我的匯編代碼:
;* int power(int x, int y); *
;*****************************************************************************
%define y [ebp+12]
%define x [ebp+8]
%define z [ebp-4]
power:
push ebp
mov ebp,esp
sub esp,16
mov byte[ebp-4], 1
jmp L3;
L1:
mov eax,[ebp+12]
and eax,0x1
test eax,eax
je L2;
sub byte[ebp+12],1
mov eax,[ebp-4]
imul eax, [ebp+8]
mov [ebp-4],eax
jmp L3;
L2:
mov eax,[ebp+12]
mov edx,eax
shr edx,31
add eax,edx
sar eax,1
mov [ebp+12],eax
mov eax,[ebp+8]
imul eax,[ebp+8]
mov [ebp+8],eax
L3:
cmp byte[ebp+12],0
jg L1;
mov eax,[ebp-4]
leave
ret
當我運行它時,這是我的輸出:
power(2, 0) returned -1217218303 - incorrect, should return 1
power(2, 1) returned 2 - correct
power(2, 2) returned -575029244 - incorrect, should return 4
power(2, 3) returned 8 - correct
有人可以幫助我找出我哪里出了問題,或者更正我的代碼,我們將不勝感激。
您要存儲一個字節,然后讀回該字節+ 3個垃圾字節。
%define z [ebp-4] ; what's the point of this define if you write it out explicitly instead of mov eax, z?
; should just be a comment if you don't want use it
mov byte[ebp-4], 1 ; leaves [ebp-3..ebp-1] unmodified
...
mov eax, [ebp-4] ; loads 4 bytes, including whatever garbage was there
使用調試器將向您顯示,此時您正在EAX中獲取垃圾。 您可以使用movzx eax, byte [ebp-4]
或首先存儲4B來修復它。
或者,更好的是,根本不使用任何額外的堆棧內存,因為您可以使用ECX,而不必按照通常的32位調用約定保存/恢復ECX。 將您的數據保存在寄存器中,這就是它們的用途。
您使用[ebp+16]
“解決方案”正在寫入調用方擁有的堆棧空間。 您只是很幸運,我想它恰好將高3個字節清零了,破壞它不會導致崩潰。
and eax,1
test eax,eax
是多余的: test eax, 1
就足夠了。 (或者,如果要銷毀eax and eax, 1
根據結果設置and eax, 1
個標志)。
您的代碼中還有很多其他效率低下的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.