-
Notifications
You must be signed in to change notification settings - Fork 1
/
remembersizeheap.h
53 lines (37 loc) · 1001 Bytes
/
remembersizeheap.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
// -*- C++ -*-
#ifndef _REMEMBERSIZEHEAP_H_
#define _REMEMBERSIZEHEAP_H_
#include "heaplayers.h"
using namespace HL;
namespace VAM {
// RememberSizeHeap: a heap that stores sizes of allocated objects in the headers and frees with the size information
template<class SuperHeap>
class RememberSizeHeap : public SuperHeap {
public:
inline void * malloc(size_t size) {
void * ptr = NULL;
Header * header = reinterpret_cast<Header *>(SuperHeap::malloc(sizeof(Header) + size));
if (header != NULL) {
ptr = header + 1;
header->size = size;
}
return ptr;
}
inline void free(void * ptr) {
Header * header = reinterpret_cast<Header *>(ptr) - 1;
SuperHeap::free(header, sizeof(Header) + header->size);
}
inline size_t getSize(void * ptr) {
Header * header = reinterpret_cast<Header *>(ptr) - 1;
return header->size;
}
private:
struct Header {
union {
size_t size;
double dummy;
};
};
}; // end of class RememberSizeHeap
}; // end of namespace VAM
#endif