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

标签 assembly malloc mips computer-architecture

我对 MIPS 汇编语言很陌生,目前正在上一门关于计算机体系结构的类(class),其中有很大一部分是关于 MIPS 编码的。我过去学习过其他几种高级编程语言(C、C#、Python),因此有一些编程基础。

我在这里的问题特别提出:MIPS 如何为堆栈中的数组分配内存?我希望回答这个问题能让我对 MIPS 有更好的全面了解,因为我对 MIPS 语言及其体系结构的概念仍有很多概念。我也不太明白指针在这方面是如何工作的......

如果有人能花时间帮助这个困惑的学生,那就太棒了! :)

最佳答案

嗯.. 你应该知道 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
}

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

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

arr: .word 0, 0 #enough space for two words, initialized to 0, arr label points to the first element 

要在堆栈上分配一个 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)

要在堆上分配空间,需要进行系统调用。在 spim 模拟器中,这是 system call 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

关于assembly - MIPS - MIPS 如何为堆栈中的数组分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19612459/

相关文章:

c - 螺旋矩阵(作为二维指针)

c - "reallocating"二维数组 C 的新内存时出现段错误

c - 通过 malloc 函数选择排序

recursion - 使用 MIPS 的双递归

assembly - 38 "D"D 位中的 6's "代表什么?

assembly - 汇编-shr指令打开进位标志?

assembly - 带有前导 $ 的 NASM 外部符号

c - 在 MIPS 中扩展或避免 addiu

recursion - MIPS 递归斐波那契数列

c - 什么是计算 floor(log(m/n)) 的有效方法,其中 m 和 n 是整数?