Malloc 宏重载也适用于对 malloc (C++) 的编译器调用吗?
Malloc macro overloading that works also for compiler calls to malloc (C++)?
我发现在线多次提到以下 "overload" 调用 `malloc' 的技巧:
void* myMalloc(const char* file, int line, size_t size)
{
return malloc(size);
}
#define malloc(X) myMalloc( __FILE__, __LINE__, (X) )
但是,它是否也影响编译器对 malloc
的隐式调用或仅影响程序员显式进行的调用?有没有办法重载它,甚至自动调用 malloc
也会使用修改后的版本?
我问是因为我尝试了以下方法,但没有成功:
#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;
}
我的输出 returns usedMem
为零。它是,没有使用 myMalloc
分配内存。有办法实现吗?
Does it, however, also affect the implicit calls made by the compiler to malloc or only the calls made explicitly by the programmer?
仅限程序员明确进行的调用。它还会破坏任何名为 malloc
.
的成员函数
Is there a way to overload it in such a way that even the automatic calls to malloc will use the modified version?
不适用于宏。
我发现在线多次提到以下 "overload" 调用 `malloc' 的技巧:
void* myMalloc(const char* file, int line, size_t size)
{
return malloc(size);
}
#define malloc(X) myMalloc( __FILE__, __LINE__, (X) )
但是,它是否也影响编译器对 malloc
的隐式调用或仅影响程序员显式进行的调用?有没有办法重载它,甚至自动调用 malloc
也会使用修改后的版本?
我问是因为我尝试了以下方法,但没有成功:
#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;
}
我的输出 returns usedMem
为零。它是,没有使用 myMalloc
分配内存。有办法实现吗?
Does it, however, also affect the implicit calls made by the compiler to malloc or only the calls made explicitly by the programmer?
仅限程序员明确进行的调用。它还会破坏任何名为 malloc
.
Is there a way to overload it in such a way that even the automatic calls to malloc will use the modified version?
不适用于宏。