MIPS:如何在动态内存(堆)中存储字符串
MIPS: how to store a string in dynamic memory (heap)
我想编写一个子例程,将字符串作为参数(来自用户输入)并存储在动态内存中。
这是我想出的:
.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
但我觉得这不是正确的方法。
另外,之后如何释放 space?
But I have got a feeling this isn't the correct way to do it.
不,您目前只是将字符串的地址存储在堆分配的内存中。如果你想存储它的内容你需要一个循环:
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
Also how do I free the space afterwards?
假设模拟器的 sbrk
调用主机 OS 的 sbrk
您可以将负值传递给 sbrk
以缩小程序的堆。
我想编写一个子例程,将字符串作为参数(来自用户输入)并存储在动态内存中。
这是我想出的:
.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
但我觉得这不是正确的方法。
另外,之后如何释放 space?
But I have got a feeling this isn't the correct way to do it.
不,您目前只是将字符串的地址存储在堆分配的内存中。如果你想存储它的内容你需要一个循环:
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
Also how do I free the space afterwards?
假设模拟器的 sbrk
调用主机 OS 的 sbrk
您可以将负值传递给 sbrk
以缩小程序的堆。