So I’m trying to create a factorial function in assembler
In c:
#include<stdio.h>
int fat (int n)
{
if (n==0) return 1;
else return n*fat(n-1);
}
int main (void){
printf("%d\n", fat(4));
return 0;
}
In Assembly:
.text
.global fat
fat:push %ebp
mov %esp, %ebp
movl $1,%eax
movl 4(%ebp),%edx
LOOP:cmp $0,%edx
je FIM
sub $1,%edx
push %edx
call fat
imul %edx,%eax
FIM:mov %ebp, %esp
pop %ebp
ret
I keep getting the segmentation fault error and I don’t know why…can someone help me?
The offset is probably wrong in this line:
The stack has the previous value of
%ebpand the return address already, so your offset is going to have to be more than 4.I recommend stepping through the assembly code with the debugger, and make sure that all the register values are exactly what you expect them to be. You will also have problems with the
%edxregister across calls unless you save and restore its value, too.