Last Updated: July 12, 2018
·
751
· themichael'tips

Hook TCMalloc

The most easy way to hook dynamic (heap) memory allocation/deletion once that tcmalloc is linked to your application,

is to register your custom hook, that will be called every time a malloc,realloc,calloc,free are called and every time new/delete are used.

Here an exemple:

#include <iostream>
#include <malloc.h>
#include <cassert>

extern "C" {
typedef void (*MallocHook_NewHook)(const void* ptr, size_t size);
int MallocHook_AddNewHook(MallocHook_NewHook hook);
int MallocHook_RemoveNewHook(MallocHook_NewHook hook);

typedef void (*MallocHook_DeleteHook)(const void* ptr);
int MallocHook_AddDeleteHook(MallocHook_DeleteHook hook);
int MallocHook_RemoveDeleteHook(MallocHook_DeleteHook hook);
}   // extern "C"

void NewHook(const void* ptr, size_t size) {
    std::cout << "NewHook on " << ptr << " of " << size << " bytes" << std::endl;
}

void DeleteHook(const void* ptr) {
    std::cout << "DeleteHook on " << ptr << std::endl;
}

void init_hook() {
    assert(MallocHook_AddNewHook(&NewHook));
    assert(MallocHook_AddDeleteHook(&DeleteHook));
}

void destroy_hook() {
    assert(MallocHook_RemoveNewHook(&NewHook));
    assert(MallocHook_RemoveDeleteHook(&DeleteHook));
}

int main(void) {
    init_hook();
    {
        auto* ptr = malloc(100);
        ptr = realloc(ptr,200);
        auto* c = calloc(400,200);
        auto* i = new int;

        free(ptr);
        free(c);
        delete i;
    }
    destroy_hook();
    return 0;
}

Possible Output :

NewHook on 0x1a30000 of 100 bytes  #malloc
NewHook on 0x1a34000 of 200 bytes  #realloc
DeleteHook on 0x1a30000                   #realloc may delete the allocated pointer  
NewHook on 0x1a38000 of 80000 bytes  #calloc: 400*200 = 80000 bytes
NewHook on 0x1a24010 of 4 bytes  #new int
DeleteHook on 0x1a34000               #free(ptr)
DeleteHook on 0x1a38000               #free(c)
DeleteHook on 0x1a24010               #delete i