奇怪的 MIPS 地址行为

Strange MIPS address behaviour

我是 MIPS 的新手,仍在摸索一些基本命令,目前我遇到了一个非常奇怪的情况,我有 2 个相同的代码,但一个运行,另一个不运行。

这是在第 sw $v0, input 行 运行 时抛出异常的代码:

.data

Text_output1: .asciiz "Input number 1: "
input: .word

.text
main:
li $v0, 4
la $a0, Text_output1
syscall

li $v0, 5
syscall

sw $v0, input
li $v0, 1
lw $a0, input
add $a0, $a0, 1
syscall

这是正常运行的:

# Program: Hello, World!
.data

# data declaration section; specifies values to be stored
# in memory and labels whereby the values are accessed

Greeting: .asciiz "\nghfhgfhgf\n"
Text_output1: .asciiz "Number 1 : "
input: .word

.text # Start of code section
main: # Execution begins at label "main"
li $v0, 4 #in ra number 1 :
la $a0, Text_output1
syscall

li $v0, 5
syscall

sw $v0, input
li $v0, 1
lw $a0, input
add $a0, $a0, 1
syscall

我看不出两者之间有什么区别,或者我对这种语言有什么不了解的地方吗?

顺便说一句,我使用 MARS 4.5 和 JDK13。非常感谢。

如果您正在编写任何 MIPS 程序集,您应该获取官方指令集参考(MIPS32™ 程序员架构 第二卷:MIPS32™ 指令集).

对于 sw 指令,它声明如下:

Restrictions:
The effective address must be naturally-aligned. If either of the 2 least-significant bits of the address is non-zero, an Address Error exception occurs.

正如模拟器明确指出的那样,您在地址 0x0040001c 处有一条 sw 指令试图写入地址 0x10010011,该地址不是字对齐地址。

你的第二个例子碰巧成功了,因为你的两个字符串占用了 24 个字节的内存,所以 input 标签从 .data 部分的开头结束了 24 个字节,这是一个字对齐的地址。

为确保正确对齐,请使用 .align 指令,例如:

.align 2
input: .word 0

还要注意 .word 之后的 0。如果您省略初始值而只写 .word 如果您添加更多变量(它们都将获得相同的地址),您将 运行 遇到问题。