689fb6a5f4c4781f17aa82d704ffd4538d41a7f9
[c11tester.git] / mallocwrap.cc
1 #include "common.h"
2
3 /* for RTLD_NEXT */
4 #ifndef __USE_GNU
5 #define __USE_GNU
6 #endif
7
8 #include <dlfcn.h>
9 #include <new>
10
11 static void * (*real_malloc)(size_t) = NULL;
12 static void (*real_free)(void *ptr) = NULL;
13
14 static void __my_alloc_init(void) {
15   real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
16   real_free = (void (*)(void *))dlsym(RTLD_NEXT, "free");
17   if (real_malloc == NULL || real_free == NULL) {
18     fprintf(stderr, "Error in `dlsym`: %s\n", dlerror());
19     return;
20   }
21 }
22
23 void * myMalloc(size_t size) {
24   if (real_malloc == NULL)
25     __my_alloc_init();
26
27   return real_malloc(size);
28 }
29
30 void myFree(void *ptr)
31 {
32   if (real_free == NULL)
33     __my_alloc_init();
34
35   real_free(ptr);
36 }
37
38 void * operator new(size_t size) throw(std::bad_alloc)
39 {
40   return myMalloc(size);
41 }
42
43 void operator delete(void *p) throw()
44 {
45   myFree(p);
46 }