| 1 | /* -*- C++ -*- */ |
| 2 | |
| 3 | |
| 4 | #ifndef HL_DEBUGHEAP_H_ |
| 5 | #define HL_DEBUGHEAP_H_ |
| 6 | |
| 7 | #include <assert.h> |
| 8 | #include <stdlib.h> |
| 9 | |
| 10 | /** |
| 11 | * |
| 12 | * |
| 13 | */ |
| 14 | |
| 15 | namespace HL { |
| 16 | |
| 17 | template <class Super, |
| 18 | char freeChar = 'F'> |
| 19 | class DebugHeap : public Super { |
| 20 | private: |
| 21 | |
| 22 | enum { CANARY = 0xdeadbeef }; |
| 23 | |
| 24 | public: |
| 25 | |
| 26 | // Fill with A's. |
| 27 | inline void * malloc (size_t sz) { |
| 28 | // Add a guard area at the end. |
| 29 | void * ptr; |
| 30 | ptr = Super::malloc (sz + sizeof(size_t)); |
| 31 | if (ptr == NULL) { |
| 32 | return NULL; |
| 33 | } |
| 34 | size_t realSize = Super::getSize (ptr); |
| 35 | assert (realSize >= sz); |
| 36 | for (size_t i = 0; i < realSize; i++) { |
| 37 | ((char *) ptr)[i] = 'A'; |
| 38 | } |
| 39 | size_t * canaryLocation = |
| 40 | (size_t *) ((uintptr_t) ptr + realSize - sizeof(size_t)); |
| 41 | *canaryLocation = (size_t) CANARY; |
| 42 | return ptr; |
| 43 | } |
| 44 | |
| 45 | // Fill with F's. |
| 46 | inline void free (void * ptr) { |
| 47 | if (ptr) { |
| 48 | size_t realSize = Super::getSize(ptr); |
| 49 | // Check for the canary. |
| 50 | size_t * canaryLocation = |
| 51 | (size_t *) ((uintptr_t) ptr + realSize - sizeof(size_t)); |
| 52 | size_t storedCanary = *canaryLocation; |
| 53 | if (storedCanary != CANARY) { |
| 54 | abort(); |
| 55 | } |
| 56 | for (unsigned int i = 0; i < realSize; i++) { |
| 57 | ((char *) ptr)[i] = freeChar; |
| 58 | } |
| 59 | Super::free (ptr); |
| 60 | } |
| 61 | } |
| 62 | }; |
| 63 | |
| 64 | } |
| 65 | |
| 66 | #endif |