MIPS Strcpy打印出垃圾

问题描述 投票:2回答:1

所以这是我的代码,给定的参数,这是我的代码最终打印的内容。

测试函数_strCopy

请输入字符串:测试

您刚刚进入:测试

_strCopy的结果。0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz

如果两个字符串相同,你的_strCopy就能正常工作。

说实话汇编让我最头疼,考虑到大部分代码已经帮我完成了,我想这应该是很容易的,我只需要做函数就可以了。任何帮助都会被感激,谢谢。

编辑1:删除了不需要的行编辑2:解决了,只好改了

    move $t0, $a0
    move $t1, $a1

变成

    move $t0, $a1
    move $t1, $a0

这就解决了

# Arguments:
#   - $a0: An address of the first character of a source string
#   - $a1: An address of a buffer
# Return Value:
#   - None
_strCopy:
    move $t0, $a0
    move $t1, $a1
strCopy_loop:
    lbu $t3, 0($t1)  # load
    sb $t3, 0($t0)  # write
    addi $t0, $t0, 1
    addi $t1, $t1, 1
    beq $t3, $zero, __strCopy_end   # Return if we hit a null terminator
    j strCopy_loop
__strCopy_loop2:
    addi $t2, $t2, -1
    sb $zero, 0($t2)
__strCopy_end:
    sub $v0, $t0, $a0
    jr $ra
assembly mips strcpy
1个回答
0
投票

另一种可能的实现方式。

.globl my_strcpy
.ent my_strcpy
my_strcpy:
    // Arguments:
    // a0: new str
    // a1: source str
    // a2: number of chars to copy

    li $t0, 0                // New str
    li $t1, 0                // Source str
    li $t2, 0                // Char to copy
    li $t3, 0                // Chars copied

    for:
        addu $t1, $a1, $t3     // Point to next char of source str
        lb $t2, 0($t1)         // Get next char of source str

        addu $t0, $a0, $t3     // Point to next char of new str
        sb $t2, 0($t0)         // Save next char of new str

        addi $t3, $t3, 1       // +1 chars copied   
        bne $a2, $t3, for      // Continue if there are more chars 

    jr $ra                     // Back to caller

.end my_strcpy

它可以在C脚本上进行测试,就像下面这样。

#include <stdio.h>

extern void my_strcpy( char* d, char* s, size_t n );

void check( char* a, char* b, size_t n ){
    for( size_t i = 0; i < n; i += 1 ){
        if( a[i] != b[i] ){
            printf( "NOT OK \n" );
            return;
        }
    } 
    printf( "OK \n" );
}


int main(){
    char s[14] = "String sample"; // null terminator
    char d[14];
    my_strcpy( d, s, 14 );
    check( d, s, 14 );

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.