ARM程序集分段错误

时间:2016-02-18 14:25:13

标签: assembly arm

所以我只是在覆盆子pi(用于ARM处理器)上运行我的代码,并且在运行可执行文件时抛出了分段错误。以下是我如何编译它:

gcc -o cw2 cw2.s

我无法弄明白为什么!它需要输入文件来表示字符流(只是文本)。

这是我的ARM汇编代码:

.global main
.global printf
.global fopen
.global fclose
.global getc

main:
    ; Open File
    PUSH {R1} ; Push address of R1 onto stack
    LDR R0, [R1, #0x04] ; Get argv[1] from stack to R0
    LDR R1, =r ; Load address of file open format (read)
    BL fopen ; Open file
    LDR R1, =fin ; Load address of file in to R1
    STR R0, [R1] ; Store contents of R1 into R0

    ; Setup array
    LDR R4, =ch_array ; Array address
    MOV R3, #0 ; Array index

    BL loopFile
    BL printArray

@ Loop through the file
loopFile:
    LDR R1, =fin ; Load R1 with address of file in
    LDR R0, [R1] ; Load R0 with pointer? of R1
    BL getc ; Get next character from file into R0?
    CMP R0, #-1 ; Check for end of file
    BEQ endl ; Close file

    ; get index from character (getc)
    /*
        Assuming the base address is in R4 (my array), the ascii is in R0
        from the file input into R0: increment the word in memory at
        the address 'R4 + (R0 * 4)'. *4 because each word is 4 bytes.
    */
    LSL R0, R0, #2
    LDR R1, [R4, R0]
    ADD R1, R1, #1
    STR R1, [R4, R0]

    B loopFile ; Run loop again

@ Close the file
endl:
    LDR R1, =fin ; Load R1 with address of file in
    LDR R0, [R1] ; Load R0 with pointer? of R1
    BL fclose ; Close the file

printArray:
    CMP R3, #ARRAY_MAX ; while (i < ARRAY_MAX)
    BEQ _exit ; Exit if max

    ; Check if value of the array at index i where
    ; (i = character number) is 0, if so then skip it
    ; else print it

    B printArray ; Loop next iteration of array

_exit:
    MOV R7, #1
    MOV R0, #0
    SWI 0

.data
    .equ ARRAY_MAX, 255
    ch_array:
        .rept ARRAY_MAX ;For all elements in array, repeat:
        .word 0x00 ;Initialize to 0
        .endr ;End repetition
    fin:   .word 0x00
    r:     .asciz "r"
    space: .word ' '
    nl:    .word '\n'

我也不知道如何测试打印数据以确定它是否实际读取任何内容。

1 个答案:

答案 0 :(得分:0)

只是看一下前景,好像你没有检查fopen函数是否可以打开文件。如果不能,返回将为NULL并且可能导致getc中的异常。

希望它有所帮助。