forked from leavengood/Haiku-Browser
/
LeakTracker.h
123 lines (94 loc) · 2.01 KB
/
LeakTracker.h
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#ifndef __LEAKTRACKERTEST_H
#define __LEAKTRACKERTEST_H
// This code is from:
// http://www.flipcode.com/archives/How_To_Find_Memory_Leaks.shtml
// I have modified it some.
#ifdef DEBUG
#if __GNUC__ > 2
#include <string.h>
using namespace std;
#endif
#include <vector>
typedef struct {
int address;
size_t size;
char file[64];
int line;
} ALLOC_INFO;
typedef vector<ALLOC_INFO*> AllocList;
AllocList *allocList;
void AddTrack(int addr, size_t asize, const char *fname, int lnum)
{
ALLOC_INFO *info;
if (!allocList) {
allocList = new(AllocList);
}
info = new(ALLOC_INFO);
info->address = addr;
strncpy(info->file, fname, 63);
info->line = lnum;
info->size = asize;
allocList->insert(allocList->begin(), info);
};
void RemoveTrack(int addr)
{
AllocList::iterator i;
if (!allocList)
return;
for (i = allocList->begin(); i < allocList->end(); i++)
{
if((*i)->address == addr)
{
allocList->erase(i);
break;
}
}
};
int unfreedCount()
{
return allocList->size();
}
bool nothingUnfreed()
{
return allocList->empty();
}
#include <stdio.h>
void OutputDebugString(char *str)
{
printf(str);
}
void DumpUnfreed()
{
AllocList::iterator i;
int totalSize = 0;
char buf[1024];
if (!allocList)
return;
for (i = allocList->begin(); i < allocList->end(); i++) {
sprintf(buf, "%-50s:\t\tLINE %d,\t\tADDRESS %d\t%d unfreed\n",
(*i)->file, (*i)->line, (*i)->address, (int)(*i)->size);
OutputDebugString(buf);
totalSize += (*i)->size;
}
sprintf(buf, "-----------------------------------------------------------\n");
OutputDebugString(buf);
sprintf(buf, "Total Unfreed: %d bytes\n", totalSize);
OutputDebugString(buf);
};
inline void *operator new(size_t size, const char *file, int line)
{
void *ptr = (void *)malloc(size);
AddTrack((int)ptr, size, file, line);
return(ptr);
};
inline void operator delete(void *p) throw()
{
RemoveTrack((int)p);
free(p);
};
#define DEBUG_NEW new(__FILE__, __LINE__)
#else
#define DEBUG_NEW new
#endif
#define new DEBUG_NEW
#endif // __LEAKTRACKERTEST_H