Reputation: 1106
I'm a beginner at assembly, and I'm having a hard time getting sbrk to allocate memory the way I want it to. I ultimately want to create a 2D array, first by allocating one column and then going through each of the row, allocating one row at a time. However, I noticed that when I use sbrk for the second time, it does't start from an unused memory location but overwrites the memory address that I already allocated. So to find out what I'm doing wrong, I decided to use a 1D array for now.
When I first use the
li $a0, 3 # array of length 3
li $v0, 9
syscall
it allocates memory block 0x10040000
. Then I input 3 integers to those three locations that I allocated. After that, I do another sbrk just to see what address it starts from. When I do that it allocates 0x10040004
, overwriting one of the integers that I input. Following is the code that I used.
# test with 1D array
# $s0 => length of array
# $s1 => address of first element in array
# $s2 => address of second sbrk
li $s0, 3
move $a0, $s0
li $v0, 9
syscall
move $s1, $v0
# use $t1 to go through array
move $t1, $s1
# read first int
li $v0, 5
syscall
sw $v0, ($t1)
addi $t1, $t1, 4
# read second int
li $v0, 5
syscall
sw $v0, ($t1)
addi $t1, $t1, 4
# read third int
li $v0, 5
syscall
sw $v0, ($t1)
# use sbrk for second time
li $a0, 5
li $v0, 9
syscall
move $s2, $v0
# exit
li $v0, 10
syscall
When this program finishes, $s1 = 0x10040000
and $s2 = 0x10040004
.
Why does sbrk allocate memory starting from where it's already allocated? Is there any way to tell it to start from a specific address? Please correct me if I'm doing something that doesn't make sense.
Upvotes: 2
Views: 1762
Reputation: 93690
The units you should pass sbrk
are bytes. 3 integers is 3 * sizeof(int)
or (on most architectures) 12.
Upvotes: 1