我有一個非常大的項目。我試圖監視分配和釋放的內存。這是我試過的示例程序。但是,我看到它只是打印新的函數名稱,我理解。問題是如何打印函數名稱,調用者的行號。如何在重載的新操作符中打印調用者函數名稱?
main.cpp
:
#include <QtCore/QCoreApplication>
#include <cstdlib>
#include <stdio.h>
#include <fstream>
#include <memOperation.h>
#include <DumpMemory.h>
#define BUFFER (4)
class MemPlay;
#define LOG_STRING()\
{\
std::ofstream dumpfile; \
dumpfile.open("/export/home/joshis1/DBG_REC.log"); \
dumpfile<<"FUNC = "<<__FUNCTION__<<"LINE = "<<__LINE__<<std::endl; \
dumpfile.close(); \
}
void* operator new(std::size_t sz)
{
void *mem = std::malloc(sz + BUFFER);
memset(mem+sz,'PACE',4);
LOG_STRING();
return mem;
}
void operator delete(void* ptr)
{
std::free(ptr);
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MemPlay *pMemPlay1 = new MemPlay();
pMemPlay1->MyMemPlay();
return a.exec();
}
memOperation.h
#include "QDebug"
class MemPlay
{
public:
void MyMemPlay()
{
qDebug()<<"My Mem Play";
char *t = new char[10] ;
strcpy(t,"SHREYASJOSHI_SAYS_HELLO_WORLD_AND_CORRUPTS_MEMORY");
}
void FreeMemPlay(void *t)
{
delete t;
}
};
這是錯誤的結果 -
FUNC = operator newLINE = 25
可移植的,你不能。如果您使用的是GNU,請使用[backtrace](http://linux.die.net/man/3/backtrace_symbols)。 – 2015-02-24 11:55:07
您可以使用內存分析器(例如[valgrind](http://valgrind.org/docs/manual/manual.html))來查看內存分配/重新分配 – 2015-02-24 11:58:18
重載類特定的'operator new',而不是全局的: https://www.relisoft.com/book/tech/9new.html – 2015-02-24 12:05:04