assemblymipsmars-simulatorsbrk

How to free the heap memory in MIPS


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.


Solution

  • Unlike the real sbrk in UNIX, QtSpim/MARS/RARS syscall #9 doesn't support returning memory from the heap back to the system.

    But, you can implement sbrk functionality yourself, as it is fairly simple.

    malloc/free are also library routines that you can (have to, if you want them) implement yourself here, too — would be more complex involving free lists and such; these two rely on sbrk but don't necessarily require the negative argument feature depending on how they are implemented.

    For implementing the negative sbrk functionality, 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-style sbrk address and the MARS-style syscall #9 address, or, one of those or the other and a free count.

    Releasing memory (negative sbrk parameter) simply means moving the UNIX-style sbrk address back and/or increasing the free count, and otherwise doing nothing.

    Later allocations (positive sbrk parameter) 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.&sp; So, you would use a subroutine for allocatio as well, rather than using syscall #9 directly.

    In summary, you can implement your own sbrk routine taking both positive and negative amount, or implement your own malloc&free routines, or do both.  So you can manage memory but either way there's no returning memory to the outer MARS/RARS environment.