MIDAS
Loading...
Searching...
No Matches
mleak.h
Go to the documentation of this file.
1/********************************************************************\
2
3 Name: mleak.hxx
4 Created by: Stefan Ritt
5
6 Contents: Simple leak detection library based on overloading
7 of the new() and delete() operators.
8
9 Each allocation is stored in an internal _leak_list
10 and removed on the corresponding delete.
11
12 Calling mleak_print() shows the remaining allocations
13 which have not been deleted.
14
15 Use mleak_reset() to clear that list manually
16
17 Use mleak_log(true) to log each
18 allocation/de-allocation
19
20\********************************************************************/
21
22#ifndef _MLEAK_HXX
23#define _MLEAK_HXX
24
25#include <map>
26#include <sstream>
27
28static bool _mleak_log{};
29std::map<void *,std::string> _mleak_list;
30
31/*------------------------------------------------------------------*/
32
33void *operator new(std::size_t size, const char *file, int line) {
34 void *pfs = malloc(size);
35 if (pfs == nullptr) {
36 std::cerr << "No heap to allocate" << std::endl;
37 exit(-1);
38 }
39 std::stringstream s;
40 s << std::hex << pfs << std::dec << " at " << file << ":" << line << " size " << size;
41 _mleak_list[pfs] = s.str();
42
43 if (_mleak_log)
44 std::cout << "Allocated " << s.str() << std::endl;
45
46 return pfs;
47}
48
49void *operator new[](size_t size, const char *file, int line) {
50 return operator new(size, file, line);
51}
52
53void operator delete(void *pfs) noexcept {
54 if (_mleak_log)
55 std::cout << "Deleted " << std::hex << pfs << std::dec << std::endl;
56
57 // erase previous allocation from list
58 if (_mleak_list.find(pfs) != _mleak_list.end())
59 _mleak_list.erase(pfs);
60
61 free(pfs); // free pointer
62 return;
63}
64
65void operator delete[](void *pfs) noexcept {
66 operator delete(pfs);
67}
68
70 _mleak_list.clear();
71}
72
74 if (_mleak_list.size() == 0)
75 std::cout << "Leak list is empty." << std::endl;
76 else
77 std::cout << "Leak list:" << std::endl;
78
79 // print contents of list
80 for (auto &e : _mleak_list) {
81 std::cout << e.second << std::endl;
82 }
83}
84
85void mleak_log(bool flag) {
87}
88
89// replace new to catch file name and line number
90#define new new(__FILE__,__LINE__)
91
92/*------------------------------------------------------------------*/
93
94#endif // _MLEAK_HXX
void mleak_reset()
Definition mleak.h:69
void mleak_log(bool flag)
Definition mleak.h:85
std::map< void *, std::string > _mleak_list
Definition mleak.h:29
void mleak_print()
Definition mleak.h:73
static bool _mleak_log
Definition mleak.h:28
TH1X EXPRT * h1_book(const char *name, const char *title, int bins, double min, double max)
Definition rmidas.h:24
static double e(void)
Definition tinyexpr.c:136