rmorris7
2014-11-13 14:29:39
Write a MIPS assembly language program that requests dynamic allocation of memory from the operating system (malloc function) until the operating system will not allocate any more.
The malloc() library function is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. malloc takes an argument of type int to specify the number of bytes needed from the heap, and returns the base memory address of the block.
The following code segment shows how to use malloc() in assembly programs.
The malloc() library function is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. malloc takes an argument of type int to specify the number of bytes needed from the heap, and returns the base memory address of the block.
The following code segment shows how to use malloc() in assembly programs.
//assume you need a memory block to save an array of int. The array size is in register s1.
li t0, 4 #Because each integer is 4 bytes, then n integers needs n*4 bytes
mul a0, s1, t0 #calculate the number of bytes needed in memory to save n integers
jal malloc #call malloc function. It takes one argument that specifies the number of bytes to be allocated in memory.
#It returns a memory address through v0. If v0 is zero,
#memory allocation fails, and you can terminate your program. Otherwise, v0 is the base address.
#You can use the space from v0 to v0+4(n-1) to store n integers
beq v0, zero, done
move s5, v0 #save the base address at register s5