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
| #ifndef MY_ALLOC_H #define MY_ALLOC_H #include<iostream> namespace pzj {
#if 0 #include<new> #define __THROW_BAD_ALLOC throw std::bad_alloc; #elif !defined (__THROW_BAD_ALLOC) #define __THROW_BAD_ALLOC std::cout << "Out Of Memory"<< endl; exit(1); #endif
template<int inst> class __malloc_alloc_template { public: using PFUN = void(*)();
private: static void* oom_malloc(size_t n) { void* result = NULL; void (*my_malloc_handler)() = NULL; while (1) { my_malloc_handler = __malloc_alloc_oom_handler; if (my_malloc_handler == NULL) { __THROW_BAD_ALLOC; } my_malloc_handler(); result = malloc(n); if (result != NULL) { return result; } } } static void* oom_realloc(void* p, size_t n) { void* result = NULL; void (*my_malloc_handler)() = NULL; while (1) { my_malloc_handler = __malloc_alloc_oom_handler; if (my_malloc_handler == NULL) { __THROW_BAD_ALLOC; } my_malloc_handler(); result = realloc(p ,n); if (result != NULL) { return result; } } } static PFUN __malloc_alloc_oom_handler;
public: static void* allocate(size_t n) { void* result = malloc(n); if (result == NULL) { return oom_malloc(n); } return result; } static void deallocate(void* p, size_t n) { free(p); } static void* reallocate(void* p, size_t old_size, size_t new_size) { void* result = realloc(p, new_size); if (result == NULL) { oom_realloc(p, new_size); } return result; }
static PFUN set_malloc_handler(PFUN p) { PFUN old = __malloc_alloc_oom_handler; __malloc_alloc_oom_handler = p; return old; } }; template<int inst> typename __malloc_alloc_template<inst>::PFUN __malloc_alloc_template<inst>::__malloc_alloc_oom_handler = NULL;
typedef __malloc_alloc_template<0> malloc_alloc;
}
#endif
|