~jkaivo/mapalloc

388f3dfd269368b26990f86d12ea6ab1c4b7c4e6 — Jakob Kaivo 2 years ago 3077998
add optional macros to directly provide the <stdlib.h> interface
3 files changed, 35 insertions(+), 1 deletions(-)

M Makefile
M include/mapalloc.h
A test/macros.c
M Makefile => Makefile +3 -1
@@ 15,7 15,8 @@ TESTS=$(BINDIR)/overflow \
	$(BINDIR)/zero \
	$(BINDIR)/realloc \
	$(BINDIR)/use-after-free \
	$(BINDIR)/double-free
	$(BINDIR)/double-free \
	$(BINDIR)/macros

all: $(LIBDIR)/libmapalloc.a $(LIBDIR)/libwrapalloc.so



@@ 50,6 51,7 @@ $(BINDIR)/zero: $(TESTDIR)/zero.c
$(BINDIR)/realloc: $(TESTDIR)/realloc.c
$(BINDIR)/use-after-free: $(TESTDIR)/use-after-free.c
$(BINDIR)/double-free: $(TESTDIR)/double-free.c
$(BINDIR)/macros: $(TESTDIR)/macros.c

$(BINDIR)/wrapper: $(TESTDIR)/wrapper.c
	@mkdir -p $(@D)

M include/mapalloc.h => include/mapalloc.h +7 -0
@@ 9,9 9,16 @@ void *MA_realloc(void *ptr, size_t n);
void MA_free(void *ptr);

#ifdef MA_OVERRIDE_STDLIB
#undef malloc
#define malloc(n)	MA_malloc(n)

#undef calloc
#define calloc(n, e)	MA_calloc(n, e)

#undef realloc
#define realloc(p, n)	MA_realloc(p, n)

#undef free
#define free(p)		MA_free(p)
#endif


A test/macros.c => test/macros.c +25 -0
@@ 0,0 1,25 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#define MA_OVERRIDE_STDLIB
#include "mapalloc.h"

int main(void)
{
	const char buf[] = "THIS IS A CONSTANT STRING";

	char *ptr = realloc(NULL, sizeof(buf));
	memcpy(ptr, buf, sizeof(buf));
	printf("%p: %s\n", ptr, ptr);

	ptr = realloc(ptr, sizeof(buf) * 2);
	memcpy(ptr + sizeof(buf) - 1, buf, sizeof(buf));
	printf("%p: %s\n", ptr, ptr);

	ptr = realloc(ptr, sizeof(buf) * sysconf(_SC_PAGESIZE));
	memcpy(ptr + (2 * sizeof(buf)) - 2, buf, sizeof(buf));
	printf("%p: %s\n", ptr, ptr);
}