0

I'm a beginner in Assembly and I have a problem solving factorial program problem. When I compile my prog I get segmentation error, What I think the problem is at the line of ret. Here is my code:

.text
q1: .asciz "Enter a number \n"
num: .asciz "%ld\n"
fact: .asciz "%ld\n"
.global main
main:
  movq %rsp ,%rbp
  movq $0, %rax
  movq $q1, %rdi
  call printf

  subq $8,%rsp
  leaq -8(%rbp),%rsi
  movq $num, %rdi
  movq $0, %rax
  call scanf
  call factorial
factorial:
  push %rbp
  movq %rsp, %rbp
  movq 16(%rbp),%rbx
  cmpq $1,%rbx
  je endrec
  subq $1,%rbx
  pushq %rbx
  call factorial
  addq 16(%rbp),%rax
  jmp endfunc
endrec:
  movq $1,%rax
endfunc:
  movq %rbp, %rsp
  popq %rbp
  ret
Appie
  • 55
  • 5
  • Looks like you forgot to restore `%rsp` after `subq $8,%rsp`, so it's no longer pointing at the return address. Use the debugger to check that `rsp` on function entry matches the `rsp` value when `ret` executes. – Peter Cordes Dec 10 '17 at 10:51
  • 2
    oh wait a minute, you actually have two functions, but `main` falls into `factorial` instead of returning. – Peter Cordes Dec 10 '17 at 11:01
  • it works! Thank you! – Appie Dec 10 '17 at 13:49

0 Answers0