How do I get my code to stop having Segmentation Faults?

56 views Asked by At

I'm trying to get this assembly code to print out an array of random numbers and then use an insertion sort algorithim to print out a sorted list. However, my code will only print out the unsorted list and then stop at a segmentation fault.

fmt1: .string "v[%d] = %d\n"
fmt2: .string "\nSorted array:\n"
fmt3: .string "v[%d] = %d\n"

.balign 4
.global main

alloc = -(16+20+16+16) & -16
dealloc = -alloc

define(i, w9)
define(v, x10)
define(c, x9)
define(j, w18)
define(temp, w19)
define(temp64, x19)
define(offset, x11)
define(fp, x29)
define(lr, x30)

main:
    stp fp, lr, [sp, alloc]!
    mov fp, sp

    mov x8, #0
    bl srand

    mov i, 2
    str i, [fp, 36]

    add sp, sp, -8 & -16
    str wzr, [fp, -8]
    b test1

loop1:
    bl rand
    and x0, x0, #255

    str x0, [fp, -20]

    add v, fp, 16
    ldr w11, [fp, -8]
    ldr c, [fp, -20]
    lsl offset, offset, 3
    add v, v, offset
    str c, [v]

    ldr i, [fp, -8]
    add i, i, 1
    str i, [fp, -8]
test1:
    ldr i, [fp, -8]
    cmp i, 50
    b.lt loop1

    add sp, sp, 16

    str wzr, [fp, 40]
    b test2

loop2:
    ldr x0, =fmt1
    ldr w1, [fp, 40]
    add c, fp, 16
    ldr x2, [c, w1, SXTW 3]
    bl printf

    ldr i, [fp, 40]
    add i, i, 1
    str i, [fp, 40]
test2:
    ldr i, [fp, 40]
    cmp i, 50
    b.lt loop2

    mov i, #1
sort_outer_1:
    cmp i, #50
    b.gt print

    ldr temp64, [v, i, SXTW 3]
sort_inner:
    mov j, i
    cmp j, #0
    ble sort_outer_2

    ldr c, [v, j, SXTW 3]
    sxtw temp64, temp
    cmp temp64, c
    b.ge sort_outer_2

    ldr c, [v, j, SXTW 3]
    str c, [v, j, SXTW 3]

    subs j, j, #1
    b sort_inner

sort_outer_2:
    str temp64, [v, j, SXTW 3]
    add i, i, 1
    b sort_outer_1

print:
    ldr x0, =fmt2
    bl printf

    ldr x0, =fmt3
    bl printf

end:
    ldp fp, lr, [sp], dealloc
    ret

Since It was a segfault I assumed that the negative offsets were the problem since it might've been reading info from outside the stack, but putting in positve offsets gave me the same error. Then I assumed the first use of the stack was wasting 20 bytes of space, so I changed from 36 to 16. I also used gdb, and it seems this line: ( ldr c, [v, j, SXTW 3]) is the cause. Can anyone help me see whats wrong?

0

There are 0 answers