自定制operator new
代码如下:
1 #include <iostream>
2 #include <cstdlib>
3 static const int signature = 0xDEADBEEF;// signature, log in the new assigned memory
4 typedef unsigned char Byte;
5 // the decorated malloc
6 void* operator new(std::size_t size) throw(std::bad_alloc)
7 {
8 using namespace std;
9 size_t realSize = size + 2 * sizeof(int);
10 void* pMem = malloc(realSize);
11 if (!pMem) throw bad_alloc();
12
13 *(static_cast<int*>(pMem)) = signature;
14 *(reinterpret_cast<int*>(static_cast<Byte*>(pMem) + sizeof(int)
15 + size)) = signature;
16 return static_cast<Byte*>(pMem) + sizeof(int);
17 }
在gcc4.4.1下编译通过