15,471
社区成员
发帖
与我相关
我的任务
分享
#include <iostream.h>
#include <stdlib.h>
int fLogMemory = 0; // Perform logging (0=no; nonzero=yes)?
int cBlocksAllocated = 0; // Count of blocks allocated.
// User-defined operator new.
void *operator new( size_t stAllocateBlock )
{
static fInOpNew = 0; // Guard flag.
if( fLogMemory && !fInOpNew )
{
fInOpNew = 1;
clog << "Memory block " << ++cBlocksAllocated
<< " allocated for " << stAllocateBlock
<< " bytes\n";
fInOpNew = 0;
}
return malloc( stAllocateBlock );
}
// User-defined operator delete.
void operator delete( void *pvMem )
{
static fInOpDelete = 0; // Guard flag.
if( fLogMemory && !fInOpDelete )
{
fInOpDelete = 1;
clog << "Memory block " << --cBlocksAllocated
<< " deallocated\n";
fInOpDelete = 0;
}
free( pvMem );
}
int main( int argc, char *argv[] )
{
fLogMemory = 1; // Turn logging on.
if( argc > 1 )
for( int i = 0; i < atoi( argv[1] ); ++i )
{
char *pMem = new char[10];
delete[] pMem;
}
return cBlocksAllocated;
}
The preceding code can be used to detect “memory leakage” — that is, memory that is allocated on the free store but never freed. To perform this detection, the global new and delete operators are redefined to count allocation and deallocation of memory.
class X {
public:
void* operator new[] (size_t);
void operator delete[] (void*);
};
void f() {
X *pX = new X[5];
delete [] pX;
}