RCFProto
 All Classes Functions Typedefs
AllocationHook.hpp
1 
2 //******************************************************************************
3 // RCF - Remote Call Framework
4 //
5 // Copyright (c) 2005 - 2013, Delta V Software. All rights reserved.
6 // http://www.deltavsoft.com
7 //
8 // RCF is distributed under dual licenses - closed source or GPL.
9 // Consult your particular license for conditions of use.
10 //
11 // If you have not purchased a commercial license, you are using RCF
12 // under GPL terms.
13 //
14 // Version: 2.0
15 // Contact: support <at> deltavsoft.com
16 //
17 //******************************************************************************
18 
19 #include <iostream>
20 
21 #include <RCF/test/Test.hpp>
22 
23 #ifdef _MSC_VER
24 #include <RCF/test/StackWalker.h>
25 #else
26 class StackTrace {
27 public:
28  std::string toString() const { return "<Call stack unavailable>"; }
29 };
30 #endif
31 
32 bool gInstrumented = false;
33 bool gExpectAllocations = true;
34 std::size_t gnAllocations = 0;
35 
36 // User-defined operator new.
37 void *operator new(size_t bytes)
38 {
39  if (gInstrumented)
40  {
41 
42  if (!gExpectAllocations)
43  {
44  // Only flag the first unexpected allocation, so we don't end up
45  // with thousands of failures.
46 
47  gInstrumented = false;
48 
49  std::cout << "***************************************" << std::endl;
50  std::cout << "Unexpected memory allocation. Call stack:" << std::endl;
51 
52  std::cout << StackTrace().toString() << std::endl;
53 
54  std::cout << "***************************************" << std::endl;
55 
56  RCF_CHECK(0 && "Unexpected memory allocation.");
57 
58  }
59  ++gnAllocations;
60  }
61  return malloc(bytes);
62 }
63 
64 void operator delete (void *pv) throw()
65 {
66  free(pv);
67 }
68 
69 void *operator new [](size_t bytes)
70 {
71  if (gInstrumented)
72  {
73 
74  if (!gExpectAllocations)
75  {
76  // Only flag the first unexpected allocation, so we don't end up
77  // with thousands of failures.
78 
79  gInstrumented = false;
80  RCF_CHECK(gExpectAllocations);
81  std::cout << "Unexpected memory allocation." << std::endl;
82  }
83  ++gnAllocations;
84  }
85  return malloc(bytes);
86 }
87 
88 // User-defined operator delete.
89 void operator delete [](void *pv) throw()
90 {
91  free(pv);
92 }