Pini Ke
Pini Ke

Reputation: 11

Mips dynamic memory allocation and pointers

I am building a compiler with bison and encountered with this problem. I need to dynamically allocate memory and store string then print it content.

I thought about saving a pointer in the data section then allocating the memory save the address in the pointer, assign the string val then print it. my problem is when I am trying to print the string it prints only the first char. here is a code example.

.data 
    p: .word 0 # pointer to save the allocated memory first address.
.text

    li $v0,9    #allocate instruction
    li $a0,64   # allocate 64 byte
    syscall
    sw $v0,p    #save the first memory address to pointer p

    li $t0,'a'  #write the first byte 'a' cahr
    sw $t0,0($v0)
    li $t0,'b'  #write the first byte 'a' cahr
    sw $t0,4($v0)

    li $v0,4    #print instruction
    lw $a0,p
    syscall

this will result in char a on mars console. any ideas why?

Upvotes: 1

Views: 1584

Answers (2)

Pini Ke
Pini Ke

Reputation: 11

Andrew Thanks for the tip, it worked. The problem was that the syscall 4 is reading byte by byte, I was loading words so between each word mars filled with null so it printed only the first byte then stopped. The solution was to use the sb (store byte) instruction and increment the offset by 1. Thanks for your help.

Upvotes: 0

Andrew
Andrew

Reputation: 41

I'm just guessing: but chars are usually stored in bytes. Thus b should go in 1($v0) not 4($v0) and you'll need a null in 2 to terminate.

Upvotes: 1

Related Questions