无法以mips方式将字符串从一个目标复制到另一个目标?

时间:2014-03-20 00:15:56

标签: assembly mips

我似乎在将用户从一个目的地复制的字符串复制到另一个目的地时遇到了一些麻烦。在我的代码中,我从用户那里获取字符串,计算该字符串中有多少个字符,然后我尝试将它从一个地方复制到另一个地方。但是,它不起作用,它一直给我一个

Exception occurred at PC=0x00400110
  Bad address in data/stack read: 0x0000006f
  Exception 7  [Bad data address]  occurred and ignored
Memory address out of bounds

错误。这是我的代码:

.data

    prompt1: .asciiz "Please enter a string> "
    prompt2: .asciiz "The length of the string "
    prompt3: .asciiz "is: "
    string: .space 255
    newstring: .space 255
    nl: .asciiz "\n"

.text

main:

    li $v0, 4
    la $a0, prompt1
    syscall #print the first prompt

    la $a0, string
    li $a1, 255
    li $v0, 8
    syscall #get the string and put it in "array"

    la $a0, string
    li $a1, 255
    addi $s0, $s0, 0
    jal strlen #jump to strlen

    move $t0, $v0 #move whatever strlen got and put in t0
    li $v0, 4
    la $a0, prompt2
    syscall #print prompt2

    li $v0, 4
    la $a0, string
    syscall #print array

    li $v0, 4
    la $a0, prompt3
    syscall #print prompt3

    li $v0, 1
 move $a0, $t0
    syscall #print number of characters

    li $v0, 4
    la $a0, nl
    syscall #new line!

    li $v0, 4
    la $a0, nl
    syscall #againnnn!

    la $a0, newstring
    la $a1, string
    move $a2, $t0
    jal strncpy


    move $a0, $v0
    li $v0, 4
    syscall

j exit


strlen:
    lb   $s1, 0($a0)     #load next byte
    beqz $s1, firfin     #if byte is '\0', go to firfin
    addi $s0, $s0, 1     #increments character count
    addi $a0, $a0, 1     #move on to next byte
    j    strlen          #jump back and keep going

firfin:
    addi $v0, $s0, -1 #return number of chars - 1 to account for \n
    li $s0, 0 #clean up
    li $s1, 0 #sweepy sweepy
    jr   $ra

strncpy:
    lb   $s1, 0($a1)      #load next byte
    bge  $s0, $a2, secfin #if bigger than string length, jump to secfin
    sb   $a0, 0($s1)
    addi $s0, $s0, 1
    addi $a1, $a1, 1
    j strncpy
secfin:
    move $v0, $a0
    li   $s2, 0
    li   $s1, 0
    li   $s0, 0
    jr   $ra

exit:
    li $v0, 10
    syscall

1 个答案:

答案 0 :(得分:4)

strncpy中的多个问题:

  1. 在开始使用之前,您不会将$s0归零
  2. 在测试字符串结尾
  3. 之前加载一个字节
  4. 您将$a0存储到0($s1)而不是将$s1存储到0($a0)
  5. 您不会增加$a0
  6. 您不会通过修改s寄存器
  7. 来遵循调用约定
  8. 您已编码memcpy,而不是strncpy
  9. 学习使用调试器/模拟器来逐步检查代码,看看它出错了。

相关问题