0

I want to override new/delete and malloc/free. I have tcmalloc library linked in my application. My aim is to add stats.

From new I am calling malloc. Below is an example it's global.

void* my_malloc(size_t size, const char *file, int line, const char *func)
{
    void *p = malloc(size);
....
....
....
    return p;
}

#define malloc(X) my_malloc(X, __FILE__, __LINE__, __FUNCTION__)

void *
operator new(size_t size)
{
    auto new_addr = malloc(size);
....
...
    return new_addr;
}

New/delete override is working fine.

My question is what happen to other file where I have use malloc directly for example

first.cpp
malloc(sizeof(..))

second.cpp
malloc(sizeof(..))

How this malloc call get's interpret as my macro is not in header file.

eswaat
  • 733
  • 1
  • 13
  • 31
  • @iharob could you please show me one example. – eswaat Apr 18 '15 at 19:45
  • 1
    Why would you define the macro so early? – Marc Glisse Apr 18 '15 at 20:36
  • @MarcGlisse now it's working. But one question hwat happen to other file where I have use malloc ? Question updated. – eswaat Apr 18 '15 at 20:41
  • You would need to include your preprocessor macro along with your functions in each file you would like to hide the default implementations. And make sure to use include guards. However, is there any particular reason you are trying to do this? Have you heard of [valgrind](http://valgrind.org)? – Francisco Aguilera Apr 18 '15 at 20:57
  • @FranciscoAguilera yes I know little bit about valgrind, but never used it. – eswaat Apr 18 '15 at 21:06
  • @eswaat, valgrind gives you pretty detailed statistics on your memory allocations and deletions, including memory leaks. Seems like you're trying to do just that. It's also open source in case you want to collect runtime statistics on your program. – Francisco Aguilera Apr 18 '15 at 21:07

1 Answers1

0

tcmalloc provides new/delete hooks that can be used to implement any kind of tracking/accounting of memory usage. See e.g. AddNewHook in https://github.com/gperftools/gperftools/blob/master/src/gperftools/malloc_hook.h