Search code examples
stringviewinsertmipsmergesort

Why the program is showing always the same string? [+MIPS]


I need to save a data that contains: name, id and rating. So the insert command is kind this one:

addi $sp, $sp, -12
li $v0,8           # take in input
la $a0, buffer     # load byte space into address
move $t0,$a0       # save string to t0
syscall

sw $t0, 0($sp)     # name
sw $t1, 4($sp)     # id
sw $t2, 8($sp)     # rating
addi $t7,$t7,1     # number of elements

The view command is kind this one:

loop:
    beq $t6, $t7, end

    lw $a0, 0($sp)    # name
    li $v0, 4
    syscall

    lw $a0, 4($sp)    # id
    li $v0, 1
    syscall

    lw $a0, 8($sp)    # rating
    li $v0, 1
    syscall

addi $t6,$t6, 1
addi $sp,$sp, 12
j loop  

When make two elements the first one: aa, 12, 12 second one : bb, 13, 13
After the view command is this: aa, 12, 12 second one: aa, 13, 13

Can you help me solve this problem?


Solution

  • It looks like you're passing the same address (buffer) to the read_string syscall every time. So each call will overwrite the string from the previous call.

    You need to have separate buffers for every string. You could for example pass buffer to syscall 8, then calculate the length of the read string, allocate memory for it (including the NULL-terminator) using syscall 9, copy the string from buffer to your newly allocated block of memory, and finally store the address of the allocated memory on the stack instead of buffer's.