简体   繁体   中英

ARM: 2 printfs causing segmentation fault

I wrote a "Hello World" program for ARM, and it worked fine.Once I repeated the printf call (as to print "Hello World" twice) the program started to give a "Segmentation Fault" though.

Here's the code with the double printf call:

.extern printf
.global main

main:
        push {ip,lr}
        ldr r0, =test
        bl printf
        bl printf

        mov r0, #0
        pop {ip,pc}

        test: .asciz "hello world\n"

Any clues about the cause and how to fix it?

The ARM EABI specifies that the callee is allowed to change registers r0-r3 and r12, because of this your r0 does not hold the address to the string anymore. In fact it contains the return-value of the printf-call (Which would be 12 in this case). Your next printf call then would try to access a string at address 0xC in memory, which then segfaults the process.

To make the double printf work you would have to do it like this:

ldr r0, =test
bl printf
ldr r0, =test
bl printf

r0 is not only the first argument. The return value is stored therein too. Instead of a valid pointer to the string, after the first call to printf() , it will contain the number of characters printed. You want this instead:

    ldr r0, =test
    bl printf
    ldr r0, =test
    bl printf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM