使用ARM / C复制字符串

时间:2017-10-29 19:02:29

标签: 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

使用此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);
}

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

2 个答案:

答案 0 :(得分:1)

您在开始时将指针移动到原始字符串为r6,然后在之后立即覆盖长度函数中的r6。我建议将其存储在其他地方,或直接在该函数调用中使用a1

答案 1 :(得分:0)

&#39; length函数存在一些问题。

  1. 使用错误结果退出的比较
  2. 结果不允许使用尾随NUL字符
  3. 指向原始字符串的指针未递增
  4. 推荐:

    length:                         @Length function
        mov r4, #1                  @Init counter (always have trailing null)
        mov r5, r6                  @Load ptr to first character
    
    lengthLoop: 
        cmp [r5], #0                @Check for null character
        beq lengthEnd               @done
    
        add r4, r4, #1              @Add 1 to the length
        add r5, r5, #1              @step to next char in source
        b   lengthLoop              @Loop
    
    lengthEnd:
        mov pc, lr                  @return via link register