mczarnek
mczarnek

Reputation: 1383

How can I get C++ to use my own custom malloc?

I'm having a memory leak issue, and would like to make my own custom malloc/new/delete/free, etc functions. I would like to do this so that I can print a stack trace every time one of them is called, which combined with Visual Studio's heap debug tools(similar to electric fence), can be used for debugging memory leaks.

So, is there a way to tell C++ to use my own malloc? I'm using Visual Studio 2008.

Thank you.

Edit: For that matter, it would be perfectly fine if malloc executed but when it did it triggered a custom function to run as well. Somewhat wondering if _malloc_dbg could do something like that... isn't looking like it but would be nice.

Upvotes: 1

Views: 1815

Answers (3)

mczarnek
mczarnek

Reputation: 1383

To answer my own question, it turns out that you can call '_CrtSetAllocHook', which will allow you to set separate hooks to call a function anytime either an allocate, reallocate, or free are called. Which is exactly what I was looking for.

More info: https://msdn.microsoft.com/en-us/library/820k4tb8.aspx

Upvotes: 1

Thomas Matthews
Thomas Matthews

Reputation: 57729

When using the C language, just don't call malloc.

Call your own memory allocation functions and delete functions.

Upvotes: 0

zmbq
zmbq

Reputation: 39023

If you want to call a different memory allocation function, you should just call a different memory allocation function.

If you want to do that without changing your code, you can define a macro. Say you have your own allocator:

void *my_allocator(size_t size);

You can then define

#define malloc(x) my_allocator(x)

This is for malloc. In C++, you can override the new operator

Upvotes: 0

Related Questions