河内分段故障的装配塔

时间:2017-02-16 06:47:23

标签: assembly arm

.data
.set BUFFERSIZE,20

num: .word 0
frompeg: .word 0
topeg: .word 0
auxpeg: .word 0

buffer:
    .space BUFFERSIZE,0
usagemsg:
    .asciz "Enter the number of disks : "

splash:
    .asciz "The moves to solve the Tower of Hanoi are:\n"

lessmsg:
    .asciz "Tower of Hanoi makes no sense with %d disks\n"

finalprint:
    .asciz "Move disk 1 from peg %d to peg %d\n"

midprint:
    .asciz "Move disk %d from peg %d to peg %d\n"
.text
.global main
.global towers

main:
    stmfd sp!,{r4-r8,lr}   @ Save lr on the stack

    ldr r0,=usagemsg
    bl printf

    ldr r0,=buffer      @ Argument 1: buffer address
    ldr r1,=BUFFERSIZE  @ Argument 2: size of the buffer
    ldr r2,=stdin       @ Address of stdin variable in memory
    ldr r2,[r2]         @ Argument 3: value of stdin
    bl fgets

    ldr r0,=buffer
    bl atoi

    mov r1, r0

    cmp r1, #1
    blt less1

    ldr r0,=splash
    bl printf   

    mov r0, r1
    mov r1, #1
    mov r2, #2
    mov r3, #3
    bl towers

    stmfd sp!,{r4-r8,lr}  @ Restore lr from the stack
    bx lr

towers:
    stmfd sp!,{r0-r8,lr}
    @ Checks if num == 1
    cmp r0, #1
    beq done2

    sub r0, r0, #-1
    mov r4, r2
    mov r2, r3 @ 2 has auxpeg
    mov r3, r4 @ 3 has topeg
    bl towers
    add r0, r0, #1


    mov r5, r0 @ 5 has num
    mov r6, r1 @ 6 has frompeg
    mov r7, r2 @ 7 has auxpeg
    mov r8, r3 @ 8 has topeg
    mov r1, r5
    mov r2, r6
    mov r3, r8
    ldr r0,=midprint
    bl printf

    mov r0, r5
    mov r1, r7
    mov r2, r8
    mov r3, r6
    sub r0, r0, #-1
    bl towers
    ldmfd sp!,{r0-r8,lr}  @ Restore lr from the stack
    bx lr 


done2:

    ldr r0,=finalprint
    bl printf

    ldmfd sp!,{r0-r8,lr}  @ Restore lr from the stack
    bx lr  


less1:
    ldr r0,=lessmsg
    bl printf 
    ldmfd sp!,{r4-r8,lr}  @ Restore lr from the stack
    bx lr

输出:

Enter the number of disks : 3
The moves to solve the Tower of Hanoi are:
Move disk 1 from peg 1 to peg 3
Move disk 2 from peg 1 to peg 2
Segmentation Fault

我认为在递归期间我遇到了寄存器问题。我认为当一个" bl塔"被调用,它为该新函数创建了8个新寄存器,但可能并非如此。但我不知道如何解决这个问题

我在c

中写了我想要创建的内容
void towers(int num, int frompeg, int topeg, int auxpeg){
    if (num == 1)
    {
        printf("Move disk 1 from peg %d to peg %d\n", frompeg, topeg);
        return;
    }
    towers(num - 1, frompeg, auxpeg, topeg);
    printf("Move disk %d from peg %d to peg %d\n", num, frompeg, topeg);
    towers(num - 1, auxpeg, topeg, frompeg);
}

0 个答案:

没有答案