title: NASM Segmentation Fault at Return
body: <p>I am creating a program that accepts a two-digit number then prints the prime numbers from 1 to the two-digit number. After I've printed all of the prime numbers, when the program is already exiting, a seg fault shows up. How to fix this? Thank you in advance.</p>
  
  <p>Here are the subroutines that will provide the prime numbers.</p>
  
  <pre><code>;firstLoopBody, this will loop the numbers from 1 to N
  ;secondLoopBody, this will loop the numbers to be divided from the firstLoopBody
  getPrimes:
      mov ebp,esp
      call firstLoopBody
  
      ret 6
  
  firstLoopBody:
      ;loop the numbers from 1 to N
      mov ax,[ebp+6]
      cmp ax,[ebp+8]
      jne next
  
      mov eax,4
      mov ebx,1
      mov ecx,exitString
      mov edx,esLen
      int 80h
  
      ret
  
  next:
      inc word[ebp+6] ;add 1 to the firstLoop
      mov word[ebp+4],1 ;restart the value of secondLoop every getPrimes
  
  secondLoopBody:
      inc word[ebp+4]
      ;check if the secondLoop == firstLoop
      mov ax,[ebp+6]
      cmp ax,[ebp+4]
      je printOne
  
      mov dx,0
      mov ax,[ebp+6]
      div word[ebp+4]
  
      cmp dx,0 ;compare the remainder to 0
  
      jne secondLoopBody ;if the remainder is not zero, loop again
      jmp firstLoopBody ;if equal, go back to the start
  
  printOne:
      call printPrimes;print prime. if the loop has reached its end without breaking, it means that there are no divisible numbers found for the number, therefore making it a prime number
      jmp firstLoopBody
  
  printPrimes:
      sub esp,4 ;to allocate for the characters to be printed
      ;convert to characters
      mov dx,0
      mov ax,[ebp+6]
      mov cx,10
      div cx
  
      mov [ebp-4],ax
      mov [ebp-2],dx ;-2 = ones, -4 = tens
  
      add word[ebp-4],30h
      add word[ebp-2],30h
  
      ;printing
      mov eax,4
      mov ebx,1
      mov ecx,prime
      mov edx,primeLen
      int 80h
  
      mov eax,4
      mov ebx,1
      lea ecx,[ebp-4]
      mov edx,1
      int 80h
  
      mov eax,4
      mov ebx,1
      lea ecx,[ebp-2]
      mov edx,1
      int 80h
  
      mov eax,4
      mov ebx,1
      mov ecx,nl
      mov edx,nlLen
      int 80h
  
      add esp,4
  
      ret
  </code></pre>