We have to code in Assembly which is as you may know hard. Or professor didnt give us any information how to code or link properly. We had to learn it by ourselves. Tomorrow I have to hand in my work.
The aim is to print the n.th Fibonacci number to the console.
section .data
fmt: db "fib=%d",10,0
section .text
extern _printf
global _main, fib
_main:
mov eax, 10 ; e.g. n=10
mov ebx, 1 ; we know f_0 and f_1
sub eax, ebx ; thats why n--
push eax ; push n
push 0 ; f_0 = 0
push 1 ; f_1 = 1
call fib
push eax ; in eax the result is stored
push fmt
call _printf
mov ebx, 0
mov eax, 1 ; exit(0)
int 0x80
fib:
mov ecx, eax
pop esi
calc:
pop ebx
pop edx
add ebx, edx
mov eax, ebx
push edx
push ebx
sub ecx, 1
cmp ecx, 0
jne calc
push esi
ret
After struggling with the linker I finally managed to assemble and link my program. But it doesn’t work – I get a segmentation fault everytime.
Edit:
corrected code – I get some text on the console, but sadly no correct number it always displays “fib=1” and again seg fault.
You have
then
You can’t do that – the call instruction will push the return address on the stack, and that’s the first thing you’ll be popping off in fib.