Moi Kko
Moi Kko

Reputation: 1

MIPS - how to store char values into space

I tried to store a char in to a space x

        .data
x:      .space  1
        .text
        .globl main
main:
    lb  $t0, '*'
    sb  $t0, x

    lb  $a0, x
    li  $v0, 11
    syscall

        jr  $ra

it shows "Bad address in data/stack" but it works perfectly when i use int

     .data
x:      .space  4
        .text
        .globl main
main:
    li  $t0, 6
    sw  $t0, x

    lw  $a0, x
    li  $v0, 1
    syscall

        jr  $ra

Whats the difference between them? Why the int one works but the char one does not?

Upvotes: 0

Views: 2076

Answers (1)

Michael
Michael

Reputation: 58467

Judging by the system calls you're using, you're running this in a simulator like SPIM or MARS. The simulator showed you what the problem is:

Runtime exception at 0x00400000: address out of range 0x0000002a

And at address 0x00400000 in the code window you can see lb $8,0x0000002a($0).

So you're trying to load a byte from address 0x2a (0x2a happens to be the ASCII code for '*').

Indeed, if you look up LB in the instruction set reference from MIPS, you'll see:

LB rt, offset(base)
Description: rt ← memory[base+offset]

Obviously this is not the instruction you want for loading the constant value '*'. For that you should be using the li pseudo-instruction (or addi or ori).


TL;DR: You're tring to use a memory load instruction to load an immediate constant. Don't ignore the information that the simulator is giving you.

Upvotes: 2

Related Questions