x86 NASM程序集中的阶乘函数出错 [英] Factorial function in x86 NASM assembly goes wrong
问题描述
我正在使用x86 NASM学习汇编语言.我想编写一个简单的递归阶乘函数,使用EAX寄存器将一个参数传递给该函数.之后,我想在屏幕上打印结果,但是什么也没有发生.坐在电脑上凝视着我之后,我不知道我的代码有什么问题.你们可以帮助新手解决这个问题吗?
I'm learning assembly language using x86 NASM. I wanted to write a simple recursive factorial function to which I am passing one parameter using EAX register. After that, I want to print my result on the screen but nothing happens. After sitting and staring on my computer I don't have any clue what is wrong with my code. Can you guys help newbie with this problem?
我知道阶乘函数的序言和结尾不是必需的,因为我没有使用堆栈,但是对我来说代码更易读;)
I know that the prologue and epilogue of factorial funtion is not required due I'm not using stack but for me code is more readable ;)
这是我的代码:
global main
extern printf
section .data
message db "%03X", 0x10, 0x0
section .text
main:
mov eax, 5
call factorial
push eax
push message
call printf
add esp, 0x8
mov eax, 1
mov ebx, 0
int 0x80
factorial:
push ebp
push edx
mov ebp, esp
mov edx, eax
cmp edx, 0
jne not_equal_zero
mov eax, 1
jmp exit
not_equal_zero:
mov eax, edx
sub eax, 1
call factorial
imul eax, edx
exit:
mov esp, ebp
pop edx
pop ebp
ret
推荐答案
C库-我想您使用的是GCC的库-无法立即输出 printf
的结果.而是将其存储在称为缓冲区的单独内存中,并偶然输出.在这种情况下,程序将以 int 0x80/ eax = 1
结束的速度比刷新缓冲区的速度快.您可以插入手动刷新:
The C library - I guess you use the one from GCC - doesn't output the result of printf
immediately. Rather, it is stored in a separate memory called buffer and outputted by chance. In this case the program will be ended by int 0x80/eax=1
faster than the buffer will be flushed. You can insert a manual flush:
...
extern fflush
...
push 0
call fflush
add esp, 4
...
最好的解决方案是使用C exit
函数.替换
The best solution is to use the C exit
function. Replace
mov ebx,0
mov eax,1
int 0x80
作者
push 0
call exit
或简单地替换为
ret
在这种情况下,您不需要手动刷新缓冲区.这将退出
或 ret
为您完成.
In this case you don't need to flush the buffer manually. This will exit
or ret
do for you.
BTW:LF(换行符)被编码为10个十进制和0x0A十六进制.
BTW: LF (line feed) is coded as 10 decimal and 0x0A hexadecimal.
这篇关于x86 NASM程序集中的阶乘函数出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!