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?