Nobody Noname
Nobody Noname

Reputation: 91

Counting recrusive function in IA86 assembly - unexpected values

I've wrote assembly program which should count the below recursive function :

f(n) = f(n-1) + 2*f(n-2) - f(n-3)

For n = 0 and n = 1 it returns 1, and for n = 2 it should return 0. But for this values program always returns 0, it looks like the below conditions were never met.

if0:              
  mov eax,1
  jmp end
if1:               
  mov eax,1
  jmp end          
if2:               
  mov eax,0
  jmp end 

For any other value (greater than 2) I recives an segmentation falut. Below is the entire code:

.intel_syntax noprefix
.globl main
.text

main:

  mov eax, 3

  push eax
  call f

  push eax
  push offset msg
  call printf
  add esp, 8

  mov eax, 0
  ret

f:
  push    ebp        
  mov     ebp,esp   
  add     ebp,12     
  mov     ebx,[ebp]   

  cmp     ebx, 0      
  jz     if0
  cmp     ebx, 1
  jz     if1
  cmp     ebx, 2
  jz     if2

  lea ecx, [ebx-1]
  push ecx            
  call  f             
  pop ecx            

  push eax            
  lea ecx,[2*ebx-2]
  push ecx           
  call  f            
  pop ecx             
  pop eax         
  add eax,ecx        

  push eax
  lea ecx, [ebx-3]
  push ecx            
  call f             
  pop ecx             
  pop eax             
  sub eax,ecx
  jmp end

if0:              
  mov eax,1
  jmp end
if1:               
  mov eax,1
  jmp end          
if2:               
  mov eax,0
  jmp end         

end:
  pop     ebx         
  pop     ebp         
  ret

msg:    .asciz "Output = %d\n"

I have no idea what I do wrong. EDIT: So, I've experimented with ebp and I've changed add ebp,8 to: add ebp, 16. And, now it works for base conditions. It seems to me that there is problem with stack overflow, but I don't see it where is it.

Upvotes: 0

Views: 112

Answers (1)

NPE
NPE

Reputation: 500167

Your pop ebx has no corresponding push, messing up your stack. There could well be other errors, but that's the one that jumped out at me.

Upvotes: 2

Related Questions