0

Ackermann’s function A(m,n), where m ≥ 0 and n ≥ 0, is defined as

A(0, n) = n + 1
A(m + 1, 0) = A(m, 1)
A(m + 1, n + 1) = A(m,A(m+1,n))

I am trying to write the code for the above function but I am getting seg fault for m=1,n=1. What am I doing wrong?? I am using NASM assembly.

%include "io.mac"

.DATA
    str1        db          "Enter the value of m : ",0
    str2        db          "Enter the value of n : ",0
    str3        db          "A(m,n) = ",0
.UDATA
    m           resd        1
    n           resd        1
.CODE
    .STARTUP
        PutStr      str1
        GetLInt     [m]
        mov         AX,[m]
        PutStr      str2
        GetLInt     [n]
        mov         BX,[n]
        push        AX
        push        BX
        call        ackermanFunc
        jmp         end
    ackermanFunc:
        enter       0,0
        mov         AX,[EBP+10]
        mov         BX,[EBP+8]
        cmp         AX,0
        je          case1
        cmp         BX,0
        je          case2
        jmp         case3
    case1:
        mov         CX,BX
        inc         CX
        leave
        ret         4
    case2:
        dec         AX
        push        AX
        push        1
        call        ackermanFunc
        leave       
        ret         4
    case3:
        dec         BX
        push        AX
        push        BX
        call        ackermanFunc
        dec         AX
        mov         BX,CX
        push        AX
        push        BX
        call        ackermanFunc
        leave       
        ret         4
    end:
        PutStr      str3
        PutInt      CX
        nwln
    .EXIT
Mike
  • 9
  • 3
  • One problem is that your recursion needs the original value of `AX` but you do not preserve that. – Jester Apr 25 '22 at 19:03
  • Use a debugger to single-step your code and see where the segfault is. Also, in 32-bit code you probably want to use 32-bit integer registers; Ackermann's function grows extremely fast, so you'll want all the integer range you can get to avoid overflow. – Peter Cordes Apr 25 '22 at 22:22
  • @Jester original value of AX is preserved in stack right? – Mike Apr 26 '22 at 01:32
  • @PeterCordes do we have a debuggers for assembly languages? – Mike Apr 26 '22 at 01:33
  • 1
    Yes, of course! Asm is the easiest language to write a debugger for, it doesn't even need the source, it can just disassemble the machine code and show you the contents of registers and memory, since assembly language programs manipulate that state directly, not to implement a higher-level abstraction. See the bottom of https://stackoverflow.com/tags/x86/info for debugging tips. – Peter Cordes Apr 26 '22 at 02:03

0 Answers0