MIPS中数组的动态分配

时间:2012-12-15 19:49:26

标签: arrays assembly mips

我们的团队正在尝试创建一个能够提供代码并从中生成MIPS程序集的编译器。

为了解决全局范围内的数组声明,我们在.text中为数组创建一个标签,并保留4个字节以保存指向内存中数组开头的地址。

    .text
arr:    .space 4
    .data
...
li $t0, N         # (where N = number of elements in arr)
li $v0, 9         # Load system instruction to allocate dynamic memory
li $t1, 4         # 4 bytes per element
mult $t0, $t1     # Calculates how big the allocated memory has to be in bytes.
mflo $a0          # Loads this value into $a0
syscall           # Allocates memory and returns address into $v0
la $s0, arr       # load address of arr into $s0
sw $v0, ($s0)     # Save allocated memory address into the space reserved in .text

但是,最后一条指令对我们来说似乎并不合适。

This image显示错误发生的确切位置以及当时寄存器的状态。我不确定它为什么会导致错误。

编辑:有关产生的错误的更多信息,已更新为包含最后修改的说明

[00400000] 8fa40000  lw $4, 0($29)            ; 183: lw $a0 0($sp) # argc 
[00400004] 27a50004  addiu $5, $29, 4         ; 184: addiu $a1 $sp 4 # argv 
[00400008] 24a60004  addiu $6, $5, 4          ; 185: addiu $a2 $a1 4 # envp 
[0040000c] 00041080  sll $2, $4, 2            ; 186: sll $v0 $a0 2 
[00400010] 00c23021  addu $6, $6, $2          ; 187: addu $a2 $a2 $v0 
[00400014] 0c100009  jal 0x00400024 [main]    ; 188: jal main 
[00400018] 00000000  nop                      ; 189: nop 
[0040001c] 3402000a  ori $2, $0, 10           ; 191: li $v0 10 
[00400020] 0000000c  syscall                  ; 192: syscall # syscall 10 (exit) 
[00400024] 34080003  ori $8, $0, 3            ; 9: li $t0, 3 # Load immediate value into register $t0 
[00400028] 34020009  ori $2, $0, 9            ; 10: li $v0, 9 
[0040002c] 34090004  ori $9, $0, 4            ; 11: li $t1, 4 
[00400030] 01090018  mult $8, $9              ; 12: mult $t0, $t1 
[00400034] 00002012  mflo $4                  ; 13: mflo $a0 
[00400038] 0000000c  syscall                  ; 14: syscall 
[0040003c] 3c101001  lui $16, 4097 [arr0]     ; 15: la $s0, arr0 
[00400040] ae020000  sw $2, 0($16)            ; 16: sw $v0, ($s0)


PC       = 400040
EPC      = 40003c
Cause    = 1c
BadVAddr = 1004002f
Status   = 3000ff12

1 个答案:

答案 0 :(得分:3)

最后一条指令sw $v0, arr0($0) = MEM[$0 + arr0] = $v0,这是不正确的。但是,您将获得所请求的内存量,并且需要将该内存指针保存在寄存器中,直到程序范围。作业可能如下所示,

arr:    .space 4

syscall             # Allocates memory and returns address into $v0
la     $s0, arr     # arr is pointer address
st     $v0, 0($s0)  # start base address of array

现在arr是保存内存地址的4字节内存的基址。对于良好实践,重新分配分配回OS的内存为

li      $v0,10      # return back to OS
syscall