MIPS - MIPS如何为堆栈中的数组分配内存?

Sam*_*ony 10 malloc assembly mips computer-architecture

我对MIPS汇编语言很陌生,目前正在上一个关于MIPS编码的计算机体系结构课程.我以前学过其他几种高级编程语言(C,C#,Python),因此在编程方面有一些基础.

我的问题在这里特别问:MIPS如何为堆栈中的数组分配内存?我希望回答这个问题有望让我更好地理解MIPS,因为我仍然在概念化MIPS语言及其架构的概念.我不太明白指针在这方面是如何工作的......

如果有人可以花时间帮助这个迷茫的学生,那将是辉煌的!:)

Kon*_*ach 19

嗯..你应该知道MIPS,就像C一样,基本上有三种不同的内存分配方式.

考虑以下C代码:

int arr[2]; //global variable, allocated in the data segment

int main() {
    int arr2[2]; //local variable, allocated on the stack
    int *arr3 = malloc(sizeof(int) * 2); //local variable, allocated on the heap
}
Run Code Online (Sandbox Code Playgroud)

MIPS程序集支持所有这些类型的数据.

要在数据段中分配int数组,您可以使用:

.data

arr: .word 0, 0 #enough space for two words, initialized to 0, arr label points to the first element 
Run Code Online (Sandbox Code Playgroud)

要在堆栈上分配int数组,您可以使用:

#save $ra
addi $sp $sp -4  #give 4 bytes to the stack to store the frame pointer
sw   $fp 0($sp)  #store the old frame pointer
move $fp $sp     #exchange the frame and stack pointers
addi $sp $sp -12 #allocate 12 more bytes of storage, 4 for $ra and 8 for our array
sw   $ra  -4($fp)

# at this point we have allocated space for our array at the address -8($fp)
Run Code Online (Sandbox Code Playgroud)

要在堆上分配空间,需要进行系统调用.在spim模拟器中,这是系统调用9:

li $a0 8 #enough space for two integers
li $v0 9 #syscall 9 (sbrk)
syscall
# address of the allocated space is now in $v0
Run Code Online (Sandbox Code Playgroud)