Advertisement
Aslai

Untitled

Mar 21st, 2013
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. One relatively simple approach for single threaded architectures that you can take for dynamic memory management, though does require a few extra clock cycles than traditional methods, is as follows:
  2.  
  3. 1. Establish a block of memory as your heap. This should be done during OS initialization. Along with this, create space to store the address of the end of the currently used heap.
  4.  
  5. 2. Establish a block of memory to use as an array of pointer objects. Keep track of the size of the array. Each object would be a 16 bit address and a 16 bit integer.
  6.  
  7. 3. Clear the pointer array to nulls.
  8.  
  9. 4. Upon a call to malloc...
  10. 4.a. Determine if the requested space would overflow the heap by comparing the size of free heap to the size of requested heap. If it will, return null. Unlock the heap if it's locked.
  11. 4.b. If it's not, add an entry to the pointer array, which is the address of the free heap found along with the length of the block. Increase the address that points to the end of the heap by the length of the new block of memory.
  12. 4.c. Return the address to the pointer object you just created.
  13.  
  14. 5. Upon a call to free...
  15. 5.a. For debugging purposes, check and make sure the provided address points to a location in your pointer object array. Raise an error if it's not inside of the array.
  16. 5.b. Read the address of the heap from your pointer object list, and the length. Then move all the memory in the heap starting after the block you're freeing back by the length of the now vacated block to fill in the gap.
  17. 5.c. Iterate over all the pointer objects following the one that you just freed and subtract the addresses they hold by the same length, so that they're pointing to the post-move data. Subtract the length from the address of the end of the heap.
  18.  
  19. 6. To use the addresses returned by this heap system, you need to dereference the pointer to get another pointer. Usage would be similar to:
  20. [code]LD H, $2
  21. LD L, $93 ;I want 659 ($293) bytes
  22. CALL _malloc
  23.  
  24. LD A, H ;Check if null
  25. OR A
  26. JP NZ,Continue
  27. LD A,L
  28. OR A
  29. JP NZ,Continue
  30. JP MallocBarf ;Malloc returned null. There's probably a better way to do this, but I'm not all that great with assembly.
  31.  
  32. Continue:
  33. LD (MyBigArray), HL ;Save the address retrieved.
  34.  
  35. ;...
  36.  
  37. ;Let's use it.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement