RCFProto
 All Classes Functions Typedefs
AllocationHookCRT.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 <crtdbg.h>
20 #include <iostream>
21 
22 #include <RCF/test/Test.hpp>
23 
24 #include <RCF/CustomAllocator.hpp>
25 
26 #include <RCF/test/StackWalker.h>
27 
28 #ifdef NDEBUG
29 #error CRT allocator hook only possible in debug builds.
30 #endif
31 
32 bool gInstrumented = false;
33 bool gExpectAllocations = true;
34 std::size_t gnAllocations = 0;
35 
36 static _CRT_ALLOC_HOOK pfnOldCrtAllocHook = NULL;
37 
38 int crtAllocationHook(
39  int allocType,
40  void *userData,
41  size_t size,
42  int blockType,
43  long requestNumber,
44  const unsigned char *filename, // Can't be UNICODE
45  int lineNumber)
46 {
47  // Check for unexpected memory allocations.
48  if ( gInstrumented
49  && (allocType == _HOOK_ALLOC || allocType == _HOOK_REALLOC)
50  && !gExpectAllocations)
51  {
52  // Only flag the first unexpected allocation, so we don't end up
53  // with thousands of failures.
54 
55  gInstrumented = false;
56 
57  // If we do want to track further allocations, uncomment this.
58  //gInstrumented = true;
59 
60  std::cout << "***************************************" << std::endl;
61  std::cout << "Unexpected memory allocation. Call stack:" << std::endl;
62 
63  std::cout << StackTrace().toString() << std::endl;
64 
65  std::cout << "***************************************" << std::endl;
66 
67  RCF_CHECK(0 && "Unexpected memory allocation.");
68  }
69 
70  if (allocType == _HOOK_ALLOC || allocType == _HOOK_REALLOC)
71  {
72  ++gnAllocations;
73  }
74 
75  return pfnOldCrtAllocHook(
76  allocType,
77  userData,
78  size,
79  blockType,
80  requestNumber,
81  filename,
82  lineNumber);
83 }
84 
85 void setupHook()
86 {
87  pfnOldCrtAllocHook = _CrtSetAllocHook(crtAllocationHook);
88 }
89 
90 bool dummy = (setupHook(), false);