Memory alloc and deAlloc

classic Classic list List threaded Threaded
5 messages Options
Reply | Threaded
Open this post in threaded view
|

Memory alloc and deAlloc

foretopman
I must be missing something fundamental. Some of the sample code in the book and some of the other threads here talk about using Array variables for implementing the linked list of free segments. But when I call Array.new to initialize an Array, that calls Memory.alloc, which puts me into a bottomless recursion that errors out when the stack overflows.

So what am I missing?

Thanks for any help you can give
Reply | Threaded
Open this post in threaded view
|

Re: Memory alloc and deAlloc

foretopman
OK, I may have answered my own question.

Is the point that I'm calling Array.new() in alloc(), when I should be calling it in init() instead?
Reply | Threaded
Open this post in threaded view
|

Re: Memory alloc and deAlloc

cadet1620
Administrator
Array.new() is a way objects outside of Memory can allocate memory. It is just a wrapper around Memory.alloc.

What you can do in Memory, is to declare an Array object and set the object's address to an arbitrary memory address.  The is using Arrays as pointers.

At a minimum, your Memory needs a pointer to the the free list. You can type 2048 wherever you need the heap base, but the code reads better if you also make a pointer for it.
class Memory {
    static Array heap;      // Heap base pointer
    static Array freeList;  // Free List head pointer

Memory.init() is responsible for initializing the heap and the free list, and only gets called once.

For instance, if your heap block headers are two words -- next_pointer and block_size -- then you do something like this to initialize the heap as a single block and put that block on the free list.
class Memory {
    var Array block;

    // Initialize heap base,
    let heap = 2048;

    // Initialize heap as one large block.
    let block = heap;
    let block[0] = null;
    let block[1] = 14334;    // 14K-2

    // Put the block on the free list.
    let free_list = block;
    return;
}

Memory.alloc() can do similar things with Array variables to traverse the free list looking for an acceptable block.

(You can do all of this using ints and peek() and poke() but the code is much slower and uglier...)

--Mark
Reply | Threaded
Open this post in threaded view
|

Re: Memory alloc and deAlloc

foretopman
OK, thank you. I think the only thing I was missing was in thinking that I had to call Array.new() before I could use an Array variable.
Reply | Threaded
Open this post in threaded view
|

Re: Memory alloc and deAlloc

foretopman
I feel pretty stupid at this point. I can't imagine why I thought I had to call Array.new() on my Array variables in alloc() and deAlloc(). After all, I had already implemented and tested peek() and poke() with Array variables without calling Array.new().

sigh