For learning purposes, I'm trying to implement a stack in the heap memory.
When I push something I just need to do the systemcall sbrk, and that's fine.
When I proceed with a pop I can retrive my value, but I can't free the allocated space. Is there any way to do this?
The sbrk syscall doesn't accept negative numbers. I've already tried.
Unlike the real
sbrkin UNIX, QtSpim/MARS syscall #9 doesn't support returning memory from the heap back to the system.But, you can implement
sbrkfunctionality yourself, as it is fairly simple. (malloc/freewould be more complex involving free lists and such, but this is much simpler.)You need a subroutine that takes the adjustment number just like the real
sbrk, of course, and maintains a small amount of persistent/global state — maybe two words: the UNIX-stylesbrkaddress and the MARS-style syscall #9 address, or, one of those or the other and a free count.Releasing memory (negative
sbrkparameter) simply means moving the UNIX-stylesbrkaddress back and/or increasing the free count, and otherwise doing nothing.Later allocations (positive
sbrkparameter) consider the gap between markers, or free count, in allocating new heap space, and only increase underlying MARS heap if free count goes to 0 and there's still more bytes in the allocation request.