I have found online multiple mentions to the following trick to "overload" the calls to `malloc':
void* myMalloc(const char* file, int line, size_t size) { return malloc(size); } #define malloc(X) myMalloc( __FILE__, __LINE__, (X) ) Does it, however, also affect the implicit calls made by the compiler to malloc or only the calls made explicitly by the programmer? Is there a way to overload it in such a way that even the automatic calls to malloc will use the modified version?
I ask because I have tried the following, with no success:
#include <iostream> #include <malloc.h> int usedMem(0); void* myMalloc(const char* file, int line, size_t size) { usedMem += size; return malloc(size); } #define malloc(X) myMalloc( __FILE__, __LINE__, (X) ) int main(void) { int *mydata = new int[5000]; for (size_t i = 0; i < 5000; i++) { mydata [i] = 1; } std::cout << usedMem << std::endl; return 0; } My output returns zero for usedMem. It is, memory is not being allocated using myMalloc. Would there be a way to achieve that?
newoperator callsmalloc()under the hood. Even if there was, your approach will only affect your own code that callsmalloc(). If you want to redirect calls to allocate memory at a low level, you need to find out what function in your operating system's kernel is used to allocate memory and redirect it through some type of API hook -- all of which is platform specific.