简体   繁体   中英

Merging two strings in Assembly

I'm trying to merge two simple strings in assembly, in a basic fashion, eg:

String 1: AAAAAA

String 2: BBB

Result: ABABABAAA

So just alternating characters.

I've been trying to do this for a bit, but for some reason, I never reach the null terminators on my strings, and the debugger is making it impossible for me to even figure out how to find out if the strings are being combined in the first place.

        AREA HW42, CODE, READONLY

        ENTRY

        EXPORT main

main
MAX_LEN EQU 100
    LDR R8, =StrOne
    LDR R9, =StrTwo

Loop
    LDRB R3, [R8], #1
    STRB R3, [r2], #1
    LDRB r4, [r9], #1
    STRB r4, [r2], #1
    ORR R5, R3, R4
    CBZ R5, DONE
    B Loop

    LDR R8, =MixStr
    STR R3, [R8]

DONE
stop
        MOV r0, #0x18
        LDR r1, =0x20026
        SVC #0x11

        ALIGN

        AREA HWData, DATA, READWRITE
        EXPORT adrStrOne
        EXPORT adrStrTwo
        EXPORT adrMixStr

StrOne  DCB "HLO",0
StrTwo  DCB "EL",0
MixStr  SPACE MAX_LEN

adrStrOne DCD StrOne
adrStrTwo DCD StrTwo
adrMixStr DCD MixStr
        ALIGN

        END

What am I doing wrong here?

ORR R5, R3, R4
CBZ R5, DONE

This makes it probably keep going until it falls off the end of memory and faults, because your strings are different lengths:

'H' | 'E' != 0
'L' | 'L' != 0
'O' | '\0' != 0
'\0' | ??? != 0 (probably)
...

If you need to handle different-length strings, you need to check for and handle the end of each one individually.


In fact, there's no "probably" about it - due to the layout of your data, the first "???" will actually be the beginning of MixStr , which is guaranteed to be nonzero on account of being 'H' by this point, and from then on you run away copying the earlier part of the result into itself, until you fall off the end of the data section, or memory, whichever comes first.

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