Home > OS >  Malloc implementation for prologue and epilogue in C
Malloc implementation for prologue and epilogue in C

Time:11-09

I have a task that is to write my_free() and my_malloc() function.

But how do we create epilogue and prologue to properly misalign header and footer?

Supposedly we use sbrk() requries 4096 bytes from the heap.

Do I do

void* my_malloc(size_t size)
{
    void* heapspace = sbrk();
    heapspace  = 8 // ?? Do i do this to create epilogue?


}

CodePudding user response:

heapspace  = 8; 

will not align anything. If you need 8 bytes alignment, and you add 8 to the unaligned address, the result will be the same unaligned.

You need to:

void *align(void *ptr, unsigned alignment)
{
    uintptr_t addr = (uintptr_t)ptr;

    if(addr % alignment)
    {
        addr = ((addr / alignment)   1) * alignment;
    }
    return (void *)addr;
}
void* my_malloc(size_t size)
{
    char* heapspace = sbrk();
    heapspace  = sizeof(size);   //example header size
    heapspace = align(heapspace, 8);

}
  • Related