2017-01-10 97 views
0

我想编写一个以字符串作为参数(来自用户输入)并存储在动态内存中的子例程。MIPS:如何在动态内存(堆)中存储字符串

这是我想出了:

.data 
    name: .space 32 # allocates 32 bytes of memory to store a name 

    namePrompt: .asciiz "name: " 

    .text 
    .globl main 

main: 

    la $a0, namePrompt 
    li $v0, 4 # system call to print a string. 
    syscall # print namePrompt. 

    la $a0, name # adress where to store the input 
    li $a1, 32 # max input size in bytes 
    li $v0, 8 
    syscall 

    la $a0, name # name as first parameter of save_string subroutine 
    jal save_string 



save_string: 

    move $s0, $a0 # s0 = name. 

    # allocate 32 bytes in heap memory. 
    li $v0, 9 
    li $a0, 32 
    syscall 

    sw $s0, 0($v0) # store the name in allocated memory 

    jr $ra 

但是我有一种感觉,这是不这样做的正确方法。

此外,如何释放空间?

回答

1

但我有一种感觉,这不是正确的做法。

不,您目前只是将字符串的地址存储在堆分配的内存中。如果你想存储的内容,你需要一个循环:

move $s1,$v0 
copy: 
    lb $t0,($s0)  # Read one byte from the source address 
    sb $t0,($s1)  # Store it at the destination address 
    addiu $s0,$s0,1 
    addiu $s1,$s1,1 
    bne $t0,$zero,copy # Repeat until the NUL terminator has been copied 

而且我怎么释放空间后?

假设模拟器的sbrk调用主机操作系统的sbrk你可以传递一个负值sbrk缩小你的程序的堆。