From 0add2195f3e6a6e5209f2dfd5814e9e13fea156c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9=20Althaus?= Date: Tue, 2 Jun 2015 20:57:41 +0200 Subject: [PATCH] realloc is not a valid implementation for the wren reallocation function The behavior of realloc for size == 0 is implementation defined. It can return a non NULL pointer which must not be dereferenced but nether the less must be freed. When calling the wren reallocation function with size == 0 the memory pointed to ptr must be freed and NULL returned. --- src/vm/wren_vm.c | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/vm/wren_vm.c b/src/vm/wren_vm.c index d4c81a1b..53c3edfd 100644 --- a/src/vm/wren_vm.c +++ b/src/vm/wren_vm.c @@ -22,9 +22,25 @@ #include #endif +static void* defaultReallocate(void* ptr, size_t new_size) +{ + // The behavior of realloc for size == 0 is implementation defined. + // It can return a non NULL pointer which must not be dereferenced but nether + // the less must be freed. When calling the wren reallocation function with + // size == 0 the memory pointed to ptr must be freed and NULL returned. + if (ptr == NULL && new_size == 0) return NULL; + if (ptr != NULL && new_size == 0) + { + free(ptr); + return NULL; + } + + return realloc(ptr, new_size); +} + WrenVM* wrenNewVM(WrenConfiguration* configuration) { - WrenReallocateFn reallocate = realloc; + WrenReallocateFn reallocate = defaultReallocate; if (configuration->reallocateFn != NULL) { reallocate = configuration->reallocateFn;