I've been trying to make a function to store a string (passed as parameter to a function) into the heap and make it return the memory address where it's saved. For that, I've made a loop iterating into every char of the string and putting it into an allocated byte. However, I receive the message "invalid program counter value: 0x00000000"
This is what I have so far, any ideas on what might be wrong?
main:
#Parameters for function
#a0 (string)
#a1 (string size)
la $a0, string
lw $a1, size
jal saveString
#Registers planification:
#s0: string copy
#s1: where space is saved
#s2: index pointer for the loop
saveString:
sw $fp, ($sp)
sw $ra, -4($sp)
sw $s0, -8($sp)
sw $s1, -12($sp)
sw $s2, -16($sp)
move $fp, $sp
addi $sp $sp -20
move $s0, $a0
#allocate memory
li $v0, 9
move $a0, $a1
syscall
bltz $v0, saveString_noMemory
#save pointer with $v0
move $s1, $v0
#initialize array pointer
add $s2, $zero, 0
jal saveString_Loop
saveString_Loop:
beq $s2, $a1, saveString_End
lbu $t0, ($s0) #take value of string
sb $t0, ($s1) #inserto that value into one bit of allocated memory
addi $s0, $s0, 1 #point to next char of the string
addi $s1, $s1, 1 #point to next byte of allocated memory
addi $s2, $s2, 1 #i
move $v0, $t0
b saveString_Loop
saveString_NoMemory:
#todo: error message
jr $ra
saveString_End:
lw $fp, ($sp)
lw $ra, -4($sp)
lw $s0, -8($sp)
lw $s1, -12($sp)
lw $s2, -16($sp)
move $sp, $fp
jr $ra
CodePudding user response:
This seems like a calling convention error. You're saving $ra into the stack but not restoring it after you finish a function. Remember that jal will overwrite $ra. So when you do
jal saveString
you will no longer be able to return to the original function using jr $ra until you restore $ra by loading from the stack.