0

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Vavaste
  • 139
  • 1
  • 5
  • 1
    I guess you're using MARS or SPIM toy system calls, not [Linux](https://man7.org/linux/man-pages/man2/sbrk.2.html) or some other real OS with a fully functional `sbrk` library function or system call. I updated tags accordingly. – Peter Cordes Jan 02 '22 at 22:41
  • you're right, sorry but i'm a bit unexperienced in this field – Vavaste Jan 02 '22 at 23:23
  • No problem, just make sure to specify the details of whatever system you're using in future questions; it's often relevant, and at least gives context for answerers. – Peter Cordes Jan 02 '22 at 23:25
  • Does this answer your question? [MIPS - free dynamically allocated space (heap)](https://stackoverflow.com/questions/62850718/mips-free-dynamically-allocated-space-heap) – ggorlen Jan 03 '22 at 23:40

1 Answers1

2

Unlike the real sbrk in UNIX, QtSpim/MARS 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 would 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-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.

Erik Eidt
  • 23,049
  • 2
  • 29
  • 53
  • Thanks a lot, i proceeded with this solution and i'm monitoring the heap manually with two words – Vavaste Jan 02 '22 at 23:23