I'm implementing a memory manager using free list, whose node is a struct that contains meta data about the chunk of memory to be managed.
I'll call malloc() once at the very beginning to get a piece of memory from the OS. Then I'll manage it using my own program. In subsequent programs, I cannot use malloc() any more, so I have to keep the meta data (list of nodes) inside that memory. Here's my problem, suppose:
struct list *node1 = malloc(n_bytes); // only call malloc() once here
node1->memStart = node1 + sizeof(struct list) // beginning address of managable
// memory
node1->size = bytes_allocated;
node1->used = 1;
node1->next = NULL;
// starting address of node2
struct list *node2 = node1->memStart + node1->size; // used another node to track the second piece of
// that memory
node2->size = 4096;
node2->used = 0; // node2's memory is unused yet
node2->memStart = node2 + sizeof(struct list);
node2->next = NULL;
node1-next = node2; // link them
So here I'm not sure if I've written these meta data (size, used, memStart, next) to the memory address starting at node1, thus making it look like:
----------<----node1
| size |
----------
| used |
----------
|memStart|------|
---------- |
| next | |
---------- |
| |<-----|
| mem |
| |
----------<----node2
| size |
----------
| used |
----------
|memStart|
----------
| next |
----------
| |
| mem |
| |
----------
So I just wonder after the above code, whether the memory layout would be like the one drawn above. It's mainly about node2, I'm not sure if I can use it like this to write the meta data to the memory. It's important because as more and more memory is allocated, I'll need more nodes to keep track of them. I think the way to do this without malloc(otherwise it doesn't make sense to write my own manager) is to do pointer arithmetics to chop the memory into chunks and use an overhead to keep track of them.
The structure of list should be:
struct list{
int size;
void *memStart;
int used;
struct list *next;
}