« Back
in c linkers loaders object code read.

Detect heap-based allocation in C.

In most cases `malloc`, `calloc` and `realloc` uses heap-based allocation when we are using libc. For the sake of this we need to check data for where it is allocated.

How could you know that it is allocated by functions mentioned above? There is a little trick that you can do for these kind of conditions.
I was developing a linked list contruct when i am freeing the data i need to know where it belongs like HEAP or DATA segment in memory.
So I make a little trick for it. Use it without hesitation if you are using ld for linkage.

Why ld for linkage? Because we are externing ld symbol named end for determining where heap segment is located.

For more symbols take this as an example:

And this is what i have done. Let there is only a pointer with data address. (I didn't touch my code. As it is.)

void list_free(struct list_s *list)  
    void *data = NULL;
    extern void *_end;

    while(!list_empty(list->next)) {
        data = (void*)list_del(list->next);
        if(data > (void*)&_end) {
            //Free if allocated in heap
        data = NULL;
comments powered by Disqus