-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemory.cpp
executable file
·72 lines (58 loc) · 1.55 KB
/
memory.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
63
64
65
66
67
68
69
70
71
72
#include <map>
#include <cstdlib>
typedef std::map<const char*, int> countPool;
typedef std::map<void*, const char*> unmarkedPool;
countPool *allocCounts;
unmarkedPool *unmarkedAllocs;
struct MemoryManagerInitializer {
MemoryManagerInitializer() {
allocCounts = new countPool();
unmarkedAllocs = new unmarkedPool();
}
};
static MemoryManagerInitializer *memInit;
void recordAlloc(void *mem, const char *location)
{
if(!memInit)
memInit = new MemoryManagerInitializer;
(*unmarkedAllocs)[mem] = location;
(*allocCounts)[location]++;
}
void unrecordAlloc(void *mem)
{
if(!memInit)
memInit = new MemoryManagerInitializer;
const char *str = *(((const char**)mem) - 1);
if(allocCounts->find(str) != allocCounts->end())
(*allocCounts)[str]--;
else {
if(unmarkedAllocs->find(mem) == unmarkedAllocs->end())
return;
(*allocCounts)[(*unmarkedAllocs)[mem]]--;
unmarkedAllocs->erase(mem);
}
}
void *__markedAlloc(size_t size, const char *location)
{
if(!memInit)
memInit = new MemoryManagerInitializer;
void *alloc = malloc(size + sizeof(const char*));
const char **str = (const char**)alloc;
void *ret = (void*)(str+1);
*str = location;
(*allocCounts)[location]++;
return ret;
}
void dumpAllocs()
{
if(!memInit)
return;
FILE *fout = fopen("memory.log", "w");
for(countPool::iterator ii=allocCounts->begin(); ii!=allocCounts->end(); ii++)
{
if(ii->second == 0)
continue;
fprintf(fout, "%3i %s\n", (int)ii->second, (const char*)ii->first);
}
fclose(fout);
}