使用ARM/C复制字符串

use*_*853 5 c string assembly arm

所以我正在尝试学习ARM,并且正在练习从C中获取字符数组指针,复制该字符串,并返回指向不同字符数组的指针.我已经写了这段代码(评论我认为我发生了什么):

    .global copy                    @Let the linker know what's going on

copy:                           @Start
    stmfd sp!, {v1-v6, lr}      @Push stuff onto stack
    mov r6, a1                  @Put the pointer to the original string in r6
    bl length                   @Get the length of the string
    mov a1, r4                  @Put length into the input parameter
    bl malloc                   @Allocate enough memory for our new string
    mov r9, a1                  @Move the first memory location to r9

loop:                           @Loop to copy string
    ldrb r8, [r6], #1           @Load first character from string and move pointer
    strb r8, [a1], #1           @Store character in new string and move character
    subs r4, r4, #1             @Subtract 1 from length
    bne loop                    @Stop looping if string is done
    mov a1, r9                  @Move the start of the new string to the return value
    b ending                    @Go to the ending


length:                         @Length function
    mov r4, #0                  @counter set to 0
countLoop: 
    ldrb r5, [r6], #1           @Load first character
    cmp r5, #0                  @Check for null character
    add r4, r4, #1              @Add 1 to the length
    bne countLoop               @Loop if we're not at the end
    mov pc, lr                  @Return the program

ending:
    ldmfd sp!, {v1-v6, pc}      @Pop stuff off the stack
.end
Run Code Online (Sandbox Code Playgroud)

有了这个C驱动程序:

#include <stdlib.h>
extern char * copy( char str[] ) ; /* declare the assembly routine */
int main( int argc, char * argv[] )
{
   char str[] = "abcd" ;
   char * result;
   result = copy( str ) ; /* call the assembly language routine */
   printf("Will this work? %s", result);
   exit(0);
}
Run Code Online (Sandbox Code Playgroud)

但是我继续得到结果(null).显然,我的想法中有些不正确,但我不知道它是什么.任何帮助,将不胜感激!

wjm*_*ann 1

您在开始时将原始字符串的指针移至 r6,但随后您立即在 length 函数中覆盖了 r6。我建议也将其存储在其他地方,或者直接在该函数调用中使用 a1