I need some help with my assignment. My job is to create/implement malloc/free functions in C using “Explicit free list among only the free blocks” technique. I have already studied a lot of materials, but I am still stuck at some point and I do not understand some details. So my job is to create 4 functions – initialize(), allocate() ,free() and check(). I can use only one global variable void *memory – this is the block in which I can allocate my memory using alloc().
So I wanted to implement this using doubly linked-list and I created a structure:
typedef struct memoryBlock{
struct memoryBlock *prev,*next;
}memoryBlock;
And the structure for the header:
typedef struct header{
int size;
}header;
I was advised in my class to create a separate structure for a free memory block and another separate structure for an allocated block. My first idea was to distinguish the free/allocated blocks using one bit of the block size in header – set it to 1 if the block is allocated and 0 if it is free. ( I saw this technique used in implicit lists). So my question is: do I need to create a freeBlock and allocatedBlock structure for an explicit list or can I just use the one bit of the size?
The second question is: do I need a separate structure for the header/footer of the block? Or can I just write the size of the block in the header/footer as *(int *)ptr = size; ? I tried to use this in the initialize() function:
void initialize(void *ptr, int size){
memory = ptr;
*(int *)memory = size; //header
*((int *)memory + size) = size; //footer
}
Is this correct, please?
Many thanks for any help.
sizeif it is unused otherwise. If you choose bit 0 it will only work when only even numbers of memory words are allocated. I'd rather use two lists or add another element to the struct as a flag. The code will be so must clearer. - the busybee