forked from ix-project/silo
-
Notifications
You must be signed in to change notification settings - Fork 1
/
memory.cc
82 lines (69 loc) · 1.44 KB
/
memory.cc
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
#include "macros.h" // for TRAP_LARGE_ALLOOCATIONS
#ifdef TRAP_LARGE_ALLOOCATIONS
#include <new>
#include <iostream>
#include <stdlib.h>
#include <stdint.h>
#include <execinfo.h>
#include <unistd.h>
static void *
do_allocation(size_t sz, bool do_throw)
{
if (unlikely(sz > (1 << 20))) { // allocations more than 1MB are suspect
// print stacktrace:
std::cerr << "Warning: Large memory allocation (" << sz << " bytes)" << std::endl;
void *addrs[128];
const size_t naddrs = backtrace(addrs, ARRAY_NELEMS(addrs));
backtrace_symbols_fd(addrs, naddrs, STDERR_FILENO);
}
void *ret = malloc(sz);
if (unlikely(!ret && do_throw))
throw std::bad_alloc();
return ret;
}
static inline void
do_deletion(void *p)
{
free(p);
}
void*
operator new(size_t sz) throw (std::bad_alloc)
{
return do_allocation(sz, true);
}
void*
operator new(size_t sz, const std::nothrow_t&) throw ()
{
return do_allocation(sz, false);
}
void*
operator new[](size_t sz) throw (std::bad_alloc)
{
return do_allocation(sz, true);
}
void*
operator new[](size_t sz, std::nothrow_t &) throw ()
{
return do_allocation(sz, false);
}
void
operator delete(void *p) throw ()
{
return do_deletion(p);
}
void
operator delete(void *p, const std::nothrow_t &) throw ()
{
return do_deletion(p);
}
void
operator delete[](void *p) throw ()
{
return do_deletion(p);
}
void
operator delete[](void *p, const std::nothrow_t &) throw ()
{
return do_deletion(p);
}
#endif