manuzhang
manuzhang

Reputation: 3025

how to allocate space for read_string

I'm working on the Decaf programming project, a compiler that emits Mips assembly. Here's the assembly for a built-in function ReadLine which reads string from standard input.

 input:
      .space 40
 _ReadLine:
    subu $sp, $sp, 8
    sw $fp, 8($sp)
    sw $ra, 4($sp)
    addiu $fp, $sp, 8
    subu $sp, $sp, 4
    li $a1, 40
    la $a0, input
    li $v0, 8              #read_string syscall
    syscall
    la $t1, input
bloop4:
    lb $t5, ($t1)
    beqz $t5, eloop4
    addi $t1, 1
    b bloop4
eloop4:
    addi $t1, -1
    li $t6, 0
    sb $t6, ($t1)
    la $v0, input
    move $sp, $fp
    lw $ra, -4($fp)
    lw $fp, 0($fp)
    jr $ra

So I could assign the result (actually a reference) to a string

 string s = ReadLine();

Since all the user inputs are read into the same address and s is only a reference, however, following call of ReadLine will change the value pointed by s. Of course, I want variables to keep their own copies of user inputs.

I have never done Mips assembly coding before and frankly, most of the above codes are not mine. I've got a manual so any suggestion on how to implement ReadLine function which will allocate a new space for every user input?

Thanks.

Upvotes: 1

Views: 1147

Answers (1)

blackcompe
blackcompe

Reputation: 3190

Allocate space on the heap. For most simulators that's syscall 9. Instead of sending the statically allocated space, la $a0, input, send the address of the heap allocation.

Upvotes: 1

Related Questions