This file shows the use of the 4 memory allocation and de-allocation traps to allocate and release areas of common and user heaps.
Traps used are :
The example code below carries out the following tasks :
; First, allocate a 64Kb common heap area : start moveq #mt_alchp,d0 ; Trap code move.l #65536,d1 ; 64Kb required moveq #-1,d2 ; This job is the owner of the area allocated trap #1 ; Allocate the space tst.l d0 ; Did it work ? beq.s HeapOk ; Yes <handle out of memory errors here> ; We have a common heap, convert it to a user heap : HeapOk moveq #mt_lnkfr,d0 ; Trap code suba.l a6,a0 ; We need A0 to be A6 relative lea MyHeap,a1 ; Pointer to heap header move.l 0,(a1) ; Indicate this is a new heap suba.l a6,a1 ; This needs to be relative A6 as well trap #1 ; That should do it (No errors occur here) ; We now have a large 64Kb user heap allocated. lets use 200 bytes : moveq #mt_alloc,d0 ; Trap code move.l #200,d1 ; I need a 200 bytes area of user heap lea MyHeap,a0 ; MyHeap holds the address where my heap lives suba.l a6,a0 ; Ensure that MyHeap is A6 relative trap #1 ; Allocate my 200 bytes, or fail ERR_OM tst.l d0 ; Did it work ? beq.s UseHeap ; Yes <handle out of user heap memory errors here> ; Now we have allocated some user heap, use it somehow UseHeap adda.l a6,a0 ; The address we get back is relative A6, so absolute it <do something with our 200 bytes here from address (A0) onwards>
At this point in our program we can make use to the 200 bytes allocated in our user heap, allocate more chunks of space from our 64 KB allocation and so on. When we are done with the usage of the space, we can either end the job which will free up any resources allocated, or we can be tidy and do it ourselves, as follows.
; We are finished with our 200 bytes, so de-allocate it FrUser moveq #mt_lnkfr,d0 ; Trap code move.l 0(a0),d1 ; Size - assumes A0 has not changed during usage above suba.l a6,a0 ; A0 has to be relative a6 lea MyHeap,a1 ; Pointer to top of heap suba.l a6,a1 ; Which has also to be relative A6 trap #1 ; Deallocate the 200 byte area ; Finally, we are all done, so de-allocate the common heap too FrCmn lea MyHeap,a0 ; Address of the area live here move.l (a0),a0 ; Get the address of the area trap #1 ; Return 64Kb to the common heap ; Do other stuff here ...... ; Storage address for the pointer to the top of our user heap MyHeap ds.l 1 ; One long word of storage for a user heap head pointer