-
Notifications
You must be signed in to change notification settings - Fork 3
/
CatchMemoryLeak.cpp
64 lines (50 loc) · 1.32 KB
/
CatchMemoryLeak.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <fstream>
#include <map>
#include <string>
using namespace std;
struct HeapInfo_s {
basic_string<char> fileName;
unsigned long lineNo;
unsigned long adrInHeap;
unsigned long nBytes;
};
typedef map<unsigned long, HeapInfo_s*, less<unsigned long> > heapStorage_t;
heapStorage_t* heapStorage;
void saveInStorage(unsigned long addr, unsigned long nBytes, const char* fileName, unsigned long lineNo)
{
HeapInfo_s* hInfo;
if(!heapStorage) {
heapStorage = new(heapStorage_t);
}
hInfo = new (HeapInfo_s);
hInfo->adrInHeap = addr;
hInfo->fileName = fileName;
hInfo->lineNo = lineNo;
hInfo->nBytes = nBytes;
(*heapStorage)[addr] = hInfo;
};
void removeFromStorage(unsigned long addr) {
if( heapStorage) {
heapStorage_t::iterator itor;
itor = heapStorage->find(addr);
if (itor != heapStorage->end() ) {
heapStorage->erase((itor));
// delete (void*)addr;
}
}
};
void reportUnreleasedHeap() {
ofstream ofs("Leaks.txt");
if( heapStorage) {
heapStorage_t::iterator itor;
for(itor = heapStorage->begin();
itor != heapStorage->end();
++itor) {
ofs << "File Name : " << (*itor).second->fileName << endl;
ofs << "Line No : " << (*itor).second->lineNo << endl;
ofs << "Number of unreleased bytes : " << (*itor).second->nBytes << endl;
ofs << endl;
}
}
};