NASM - The Netwide Assembler

NASM Forum => Using NASM => Topic started by: c0dehunter on November 24, 2010, 03:26:56 PM

Title: I can't find error in this code
Post by: c0dehunter on November 24, 2010, 03:26:56 PM
Hello, it's been a week since I have started to write this program but still no success :(
I get "Access violation - cannot read memory at 0x000001" at the end of the program. Also, do not mind about comments, they're in my language.
Can anyone suggest what could be wrong?

Task:
Quote
In an assembler language, write recursive function that calculates the n-th term of a sequence in the series:

f(n) = f(n-3) + f(n-2), n > 2, f(0) = 1, f(1)=1, f(2) = 7

My program:

Code: [Select]
bits 32
extern _printf
global _main

section .data
izpis db "Rezultat za f(%d)= %d",10,0 ;za izpis zaporedja
n dd 0

section .text
_rekurz:
mov eax, [esp+4]       ;trenutni argument shranimo v eax

cmp eax,0 ;primerjamo, ?e je argument 0 in v tem primeru v eax shranimo 1
je .vrni1

cmp eax,1
je .vrni1

cmp eax,2 ;primerjamo argument z 2
je .vrni7

sub eax,2 ;n=n-2
mov edx, eax ;eax (n) shranimo v drug register, saj se bo vrednost eax spremenila
push eax ;na sklad potisnemo eax (n-2)
call _rekurz ;klicemo funkcijo za trenutni (n-2) - rezultat bo v eax
add esp,4 ;pobrišemo argument
mov ecx,eax ;dobljeno vrednost shranimo v ecx, za?asno

mov eax,edx ;v eax nazaj shrani tisti trenutni n (n-2)
dec eax ;in se zmanjsamo za 1 (n-2 -1 = n-3)
push eax ;in to potisnemo na sklad na naslednji klic
call _rekurz ;klicemo funkcijo za trenutni (n-3) - rezultat bo v eax
add esp,4

add eax,ecx ;rezultata seštejemo

ret

.vrni1:
mov eax,1
ret

.vrni7:
mov eax,7
ret

.konec:
ret

_main:
pushad

; klic funkcije - rad bi izracunal 10. clen
push 10
call _rekurz
add esp,4

; izpis rezultata
push eax
push 10
push dword izpis
call _printf
add esp, 8

popad
ret


Title: Re: I can't find error in this code
Post by: Frank Kotler on November 24, 2010, 04:31:49 PM
You always find it the last place you look! :)

Code: [Select]
; izpis rezultata
push eax
push 10
push dword izpis
call _printf
add esp, 8

Best,
Frank

Title: Re: I can't find error in this code
Post by: c0dehunter on November 25, 2010, 10:26:16 PM
Frank, thank you!  I have also found a flaw that registers are changinh throughout the recursion, so i'll have to use the stack.