I've been writing an implementation of malloc and was wondering if someone could help me with this problem.
Basically, I would like to reuse memory after allocating it using sbrk(), and having made certain that the memory is free.
So essentially, imagine my memory is like this
|------------------------------|
...and I do some allocations. When I allocate memory, each bit has a head (h) and data (d).
|hddddddhddd---hdd--hddd-------|
Now I've got these holes, and if I want to use say, the first gap in my diagram, how do I set it up so that it's got a head (h) and a body (dd) also?
I've gotten to the point where now I've got a pointer to the memory location I want. In C, its pointed to by a pointer. The pointer has a custom type, where "meta" is a struct I defined. So now I have
metaStruct * mypointer = the memory address.
But when I try to do
mypointer->size = 30;
Or
mypointer->buddy = 1;
I get a segfault.
The question: how do I set it up so that the memory address, which has been allocated via sbrk(), will have the form of my struct? Obviously I can't just go myPointer = malloc(sizeof(metaStruct)), because I am writing malloc itself. I'm also not interested in sbrk()'ing more space, but rather, utilizing the existing space that I'm pointing to (I want to disregard its junk data and use the space).
How do I go about doing that?