0

I get a segfault when traversing my array. I know the problem is with the array index / pointer, and I'm not doing it properly, but I cannot seem to find a decent example in the tutorials I'm using. It correctly prints the first value (100) but on the second iteration of the print_loop it segfaults. What is the correct way to increment the pointer and move to the next value in the list ?

Any advice would be greatly appreciated!

EDIT: The segfault problem was because I wasn't reloading the format into R0. (Thanks @Jester). But I still have the problem that I don't actually know how to move the pointer R5 to the next area of memory. One commenter said I'm not changing r5, so I'm not traversing the array, but I don't actually know how/what I should change it too. The "#-4" is there just because it was what they used in the tutorial I'm using. I assumed it was to align the index to the next value in the array, because of the ".balign 4".

.data
list:    .space 400
.balign 4
return:  .word 0
format:  .asciz " %d \n"

.text

.global main

main:
        ldr r1, =return
        str lr, [r1]
        mov r6, #0  @@ load zero into r6
        mov r7, #100 @@ load 100 into r7
increment:
        add r6, #1
        mov r1, r6
        ldr r3, =list
        str r1, [r3, #-4]*/
        cmp r6, r7
        blt increment

        ldr r5,=list
        mov r6, #0
print_loop:
        ldr r0, =format
        ldr r3, [r5, #-4] 
        mov r1, r3
        bl printf
        add r6, #1
        cmp r6, r7
        blt print_loop

exit:
        ldr lr, =return
        ldr lr, [lr]
        bx lr


.global printf

.end
Rick Dearman
  • 356
  • 2
  • 12
  • 1
    `printf` itself is allowed to change `r0` so the second time it probably won't be pointing at your format string causing the crash. Move the `print_loop` label up to before the `ldr r0, =format`. PS: You don't change `r5` so you are not iterating anything. It's also unclear why you have the `-4`. – Jester Sep 16 '20 at 21:16
  • 1
    For both cases of accessing the list, you want a post-increment by 4 so `str r6, [r3], #4` and `ldr r1, [r5], #4` (no need to go through another register). The orignal `[r3, #-4]` actually addressed just before the `list` and never changed. – Jester Sep 16 '20 at 23:25

0 Answers0