简体   繁体   中英

MIPS - free dynamically allocated space (heap)

I am trying to free dynamically allocated heap memory space

I've tried running this simple code but I keep getting the same error:

"request (-40) is negative heap amount (syscall 9)"

.text
li $v0,9
li $a0,40
syscall

li $v0,9
li $a0,-40
syscall

Can anyone help me understand why it is not working? Is there a different way to free space?

MARS doesn't support sbrk with negative arguments, as you can see in the source code here .

So as far as I can tell there's no way to explicitly free dynamically allocated memory when running your code in MARS.

If you free heap memory by using a negative sbrk that basically turns the heap into a stack, as only memory at the end can be returned — that is not really what the heap is about. In the heap we want to be able to free any arbitrary object, not solely the end.

So, the questions are:

  • Why do you need to release heap memory?
  • Are you really ok using the heap like a stack?

You can implement malloc & free . Though these are usually quite complicated due to their general purpose nature and performance considerations, a simple, slow one is pretty easy to write — especially if you have knowledge of your application and its limited requirements.

A truly general purpose malloc / free uses a data structure that collects the free blocks. malloc first searches that to satisfy a request, hands out an existing free block or else uses sbrk. free returns a block to the collection. (There's more to it of course: splitting large blocks, merging free blocks...)

However, if you were ok using the heap like a stack, you could maintain two pointers, one indicating where free memory starts, and another where it ends. Releasing memory most recently allocated (like sbrk(-400) ) would decrement the free memory start pointer by 400. Allocating memory would increment free memory start by the desired amount, while also moving the free memory end pointer if needed (using a sbrk of whatever size is still needed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM