Waageesh
Waageesh

Reputation: 17

implement free() function in C

I was asked a question how to implement custom free() function in C to clear memory pointer by pointer. I tried giving explanation with pointer arithmetic as below

int* ptr = malloc(sizeof(int));
int start_addr = ptr;  // Assuming ptr is at 0x0000
int end_addr = ptr+1;  // ptr+1 will increment by size of int, it will be 0x0004
int size = end_addr - start_addr;
for (int i=0; i<size; i++)
{
    *(ptr+i) = 0; // clear each bit by resetting it to 0
}

Above will clear for pre-defined datatypes in C, but then problem statement is changed little bit again. char* cptr = malloc(15); How would you clear for particular size(15) give as above? using pointer arithmetic, we can get only 1byte of address for char pointer, how do we know the end address of memory allocated for the pointer cptr ?

I have googled for solutions, but there are implementing malloc() too from sratch using struture, and then implement my_free() on top that custom malloc(). I don't want that, we will get pointer which is already pointing to some size 15 as given in above scenario, then we should be able to clear memory pointed by that pointer.

Upvotes: 0

Views: 217

Answers (1)

Pinko
Pinko

Reputation: 79

Better not do that for existing malloc

So what malloc does is managing memory on the heap. When you call malloc(), it will look for some memory that it already manages (but is currently not in use) or will request more memory via a syscall. Anyways, free() is not about zeroing the memory. Internally, malloc keeps some rather intricate data structures (several of them in parallel!), that inserts pointers into the bits of memory that are free. It is a highly optimized system, including things like handling fragmentation etc..

In other words: Don't mess with that. The reason why all the solutions you found implement their own malloc is because that is the only way this makes sense. If you were to "insert" your custom free() there, you would have to exactly understand the data structures that malloc uses and how to get pointers to the next correct free chunk.

If you want to implement a custom free() it is probably good to understand the basics of malloc first and then implement a whole custom malloc() + free(). Keep in mind that this probably only makes sense for demonstration, you won't be as efficient as the existing implementations that have been around for a long time (except maybe for some special contexts). Have an initial read here with the glibc malloc internals.

Upvotes: 1

Related Questions