MIPS汇编递归求和程序取指地址未对齐错误原因咨询
Hey there! Let's break down that frustrating alignment error you're seeing—no code fixes needed, just a clear breakdown of why it's happening repeatedly.
First, let's unpack the error message itself:
Runtime exception at 0x0040005c: fetch address not aligned on word boundary 0x00000001
This is a core MIPS architecture constraint: the lw (load word) instruction requires the memory address it accesses to be word-aligned. In MIPS, a "word" is 4 bytes, so valid addresses for lw must be divisible by 4 (e.g., 0x0, 0x4, 0x8, etc.). When your code runs lw $t0, 0($a0), the value stored in $a0 is an address like 0x1 (or any value not divisible by 4), which violates this rule—hence the crash.
Now, why would $a0 hold a non-aligned address in your stack/recursion setup? Here are the most likely culprits based on your use case:
Misaligned stack operations: MIPS expects the stack pointer (
$sp) to always stay word-aligned, since stack frames store data (return addresses, local variables, or your input digits) in 4-byte chunks. If you're adjusting$spby 1 or 2 bytes instead of 4 (e.g.,addi $sp, $sp, -1to store a single digit), you'll push the stack into a non-aligned state. When you pass a stack address to$a0for your recursive summation, that address will be off-by a byte or two, triggering thelwerror.Mismatched storage and load instructions: If you're storing each input digit as a single byte (using
sb, store byte) on the stack, but trying to load it back withlw(load word), you're asking MIPS to read 4 bytes starting from a non-aligned address. For example, if your first digit is stored at 0xfffffff7 (not divisible by 4),lwwill try to read across a word boundary, which throws the error.Recursive parameter passing misalignment: When setting up your recursive call, if you're updating
$a0to point to the next digit by incrementing it by 1 (instead of 4), each subsequent recursive call will use a more misaligned address. This compounds the issue, leading to the error every time the recursion hits thelwinstruction.
To debug this further, you could check the value of $a0 right before the lw instruction executes (most MIPS debuggers let you inspect register values at breakpoints)—if it's not a multiple of 4, that's your smoking gun.
内容的提问来源于stack exchange,提问作者a.meyer

