【发布时间】:2011-11-30 07:31:44
【问题描述】:
我正在编写一个使用 QT 库的 C++ 应用程序。我想检测我的应用程序和 QT 中的内存泄漏。因此,我使用此引用 http://lists.trolltech.com/qt-interest/2002-04/msg00933.html 重载了 main.cpp 中的 new 和 delete 运算符,但 QT 没有使用重载的运算符。显然,这似乎是一个命名空间问题。如何解决这个问题。
int numAllocUnits = 0;
ofstream myLogFile("/root/memLeak.log");
class MemoryLeak_Manav
{
public:
MemoryLeak_Manav() {
if (!myLogFile.is_open()) {
cout << "Unable to open file";
}
myLogFile << "Memory Leak Detection log File" << endl;
printf("Memory Leak Detection On ... ");
}
public:
~MemoryLeak_Manav() {
myLogFile.close();
if(numAllocUnits)
printf("\nError: Memory leak detected: %d\n\n", numAllocUnits);
else printf("\nNo memory leak detected.\n\n");
}
public:
void *operator new [] (size_t size);
void *operator new (size_t size);
void operator delete [] (void *p);
void operator delete (void *p);
};
void * MemoryLeak_Manav::operator new(size_t size)
{
void *newPtr;
numAllocUnits++;
newPtr = malloc(size);
printf("malloc [%p allocated %d bytes]\n", newPtr, size);
myLogFile << "malloc [" << newPtr << "allocated" << size << "bytes" << endl;
return newPtr;
}
void MemoryLeak_Manav::operator delete(void *p)
{
numAllocUnits--;
free(p);
}
void * MemoryLeak_Manav::operator new [] (size_t size)
{
void *newPtr;
numAllocUnits++;
newPtr = malloc(size);
printf("malloc [%p allocated %d bytes]\n", newPtr, size);
myLogFile << "malloc [" << newPtr << "allocated" << size << "bytes" << endl;
return newPtr;
}
void MemoryLeak_Manav::operator delete [] (void *p)
{
numAllocUnits--;
printf("free %p\n", p);
myLogFile << "free" << p << endl;
free(p);
}
memLeak.log 文件是空的,我也没有看到任何 printf 的消息。
【问题讨论】:
-
您不需要使用新的运算符重新编译所有 Qt 库以使其正常工作吗?
标签: c++ qt memory-leaks operator-overloading new-operator