From 1064d480bed6b57e551f3c9ffe6a6d8f29ebe92e Mon Sep 17 00:00:00 2001 From: Brian Norris Date: Wed, 4 Apr 2012 19:35:41 -0700 Subject: [PATCH] malloc: add myMalloc() and myFree() --- Makefile | 4 ++-- common.h | 3 +++ malloc.c | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) create mode 100644 malloc.c diff --git a/Makefile b/Makefile index 9e50d84..327bbb5 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,8 @@ CC=g++ BIN=libthreads -SOURCE=libthreads.cc schedule.cc libatomic.cc userprog.c model.cc +SOURCE=libthreads.cc schedule.cc libatomic.cc userprog.c model.cc malloc.c HEADERS=libthreads.h schedule.h common.h libatomic.h model.h -FLAGS=-Wall +FLAGS=-Wall -ldl all: ${BIN} diff --git a/common.h b/common.h index 19409c8..f262720 100644 --- a/common.h +++ b/common.h @@ -13,4 +13,7 @@ #define DBG() #endif +void *myMalloc(size_t size); +void myFree(void *ptr); + #endif /* __COMMON_H__ */ diff --git a/malloc.c b/malloc.c new file mode 100644 index 0000000..196be43 --- /dev/null +++ b/malloc.c @@ -0,0 +1,38 @@ +#include "common.h" + +/* for RTLD_NEXT */ +#ifndef __USE_GNU +#define __USE_GNU +#endif + +#include + +static void * (*real_malloc)(size_t) = NULL; +static void (*real_free)(void *ptr) = NULL; + +static void __my_alloc_init(void) +{ + + real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc"); + real_free = (void (*)(void *))dlsym(RTLD_NEXT, "free"); + if (real_malloc == NULL || real_free == NULL) { + fprintf(stderr, "Error in `dlsym`: %s\n", dlerror()); + return; + } +} + +void *myMalloc(size_t size) +{ + if (real_malloc == NULL) + __my_alloc_init(); + + return real_malloc(size); +} + +void myFree(void *ptr) +{ + if (real_free == NULL) + __my_alloc_init(); + + real_free(ptr); +} -- 2.34.1