2010年7月22日木曜日

c++でnew,deleteをオーバーロードする

原始的かつ強力なデバッグ方法。最近動的言語ばっかり触ってたので、メモリリークが怖くなった。そこで、newしたときにカウンタをインクリメント、deleteでデクリメントするようにしてその結果を標準出力に書き出してしまおう。

main.cpp
01#include <stdlib.h>
02#include <iostream>
03#include <new>
04 
05static size_t newCount = 0;
06 
07void *operator new(size_t size)
08{
09   ++newCount;
10   std::cout << "(" << newCount << ") " << "new " << size << "bytes" << std::endl;
11 
12   return malloc(size);
13}
14 
15void operator delete(void *p)
16{
17   --newCount;
18   std::cout << "(" << newCount << ") " << "delete " << p << std::endl;
19   free(p);
20}
21 
22class Hoge
23{
24   int a, b;
25   char c;
26   friend std::ostream &operator<<(std::ostream &os, const Hoge &h)
27   {
28      return os << h.a << " " << h.b << " " << h.c;
29   }
30public:
31   Hoge():a(), b(100),c('a'){}
32};
33 
34int main(int argc, char *argv[])
35{
36   Hoge *ar = new Hoge [10];
37 
38   for(int i=0; i<10; ++i)
39   {
40      std::cout << ar[i] << std::endl;
41   }
42   delete[] ar;
43 
44   return 0;
45}
出力
01(1) new 120bytes
020 100 a
030 100 a
040 100 a
050 100 a
060 100 a
070 100 a
080 100 a
090 100 a
100 100 a
110 100 a
12(0) delete 0x804a008
int2個、char1個のインスタンス10個でなぜ120バイト確保されるかわからなければ、パディングで調べてみるといいと思います。

参考URL

0 件のコメント:

コメントを投稿