Search code examples
cmallocfree

Malloc/free own implementation


I'm currently trying to write my own implementation of malloc, and free.

During my research I've found some implementation which request free memoryspace with:

block = sbrk(totalSize);

then there is some other code

and finally they return:

return (block + 1);

But i don't understand why the + 1 is necessary.

Another thing i don't understand why some implementation have a magic number in their struct.

I already searched the web and stackoverflow but didn't find any answers to my question.


Solution

  • So you returned memory from your allocator. All's fine, the user does something with it, and gives your free a pointer. That's it, all you get is an address.

    How are you supposed to know from an address alone:

    1. That it was allocated by you to begin with?
    2. That you haven't freed it already?
    3. How big is the memory block it points at?

    You must store some meta-data somewhere. The approach illustrated by the examples you described, is to store the meta-data right before the raw memory you give to the caller of malloc. That way, to retrieve it all you have to do is a simple bit of pointer arithmetic with the address you were handed in free.

    After that, what meta-data to store is up to you. A magic number is one way to document that the following block was allocated by you. If its bit pattern is sufficiently "distinct" then you'll rarely try to free a block you haven't allocated yourself.