I can’t quite figure out what I’m doing wrong in my assembly code. I’m trying to write a program that compares two null terminated strings that are inputted as $a0, and $a1 sometime during the “main:” section and then calls
jal hamming
to start the program.
Basically for this section I want two strings to be compared char by char until one string hits the null terminating char. Then the program stops and returns how many chars were different until termination.
I think it has to do with the jumps that I am using, but I’m not quite sure. The program is sort of long so I took the main piece that I think is the problem (hence ignore variables like $a3, that has been initialized and defined already):
diffchar:
li $t4, 0
li $t5, 1
beq $a0, $a1, samechars
move $v0, $t5
j diffcharend
samechars:
move $v0, $t4
diffcharend:
jr $ra
hamming:
absvaluedone:
li $a2, 0
#li $v0, 0
move $t0, $a0
move $t1, $a1
hammingloopbegin:
lb $t2, 0($t0)
lb $t3, 0($t1)
beq $t2, $0, hammingdone
beq $t3, $0, hammingdone
la $a0, 0($t0)
la $a1, 0($t1)
jal diffchar **#this is the line that causes me problems, if I take this out it is fine**
beq $v0, $0, next
addiu $a2, $a2, 1
next:
addiu $t0, $t0, 1
addiu $t1, $t1, 1
j hammingloopbegin
hammingdone:
add $v0, $a2, $a3
jr $ra
When I run my program my output looks like an infinite loop that keeps saying:
Exception occurred at PC=0x00400144
Bad address in data/stack read: 0x10021226
Exception 7 [Bad address in data/stack read] occurred and ignored
Exception occurred at PC=0x00400140
Bad address in data/stack read: 0x1002121b
Exception 7 [Bad address in data/stack read] occurred and ignored
I think there’s something wrong with diffchar or the process I use to jump around to diffchar. This is my first time writing assembly code so I think theres something really basic I am missing thats making this mess up. Any pointers would be great.
Thanks for the help
You do not save the return address before
jal diffchar. It returns and$rastill holds the new value. When youjr $raagain inhammingdone, you jump back to right after thediffcharcall. You need to store$rasomewhere before callingdiffcharand restore it after the call returns.Here is a good explanation of nested procedures in MIPS, which describes the problem you are experiencing and a solution using the runtime stack: