From 3a1876bdafb153924c2062a49251d7ccfcea4541 Mon Sep 17 00:00:00 2001 From: Daiki Ueno Date: Mon, 12 Oct 2020 10:35:07 +0200 Subject: [PATCH] C-Allocators: Mention `realloc` behavior if size is zero Signed-off-by: Daiki Ueno --- .../pages/programming-languages/C-Allocators.adoc | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/modules/ROOT/pages/programming-languages/C-Allocators.adoc b/modules/ROOT/pages/programming-languages/C-Allocators.adoc index 8c858f6..3a15fa2 100644 --- a/modules/ROOT/pages/programming-languages/C-Allocators.adoc +++ b/modules/ROOT/pages/programming-languages/C-Allocators.adoc @@ -43,6 +43,20 @@ compiler may assume that a comparison between the old and new pointer will always return false, so it is impossible to detect movement this way. +On a related note, `realloc` frees the memory area if the new size is +zero. If the size unintentionally becomes zero, as a result of +unsigned integer wrap-around for instance, the following idiom causes +a double-free. + +[source,c] +---- +new_size = size + x; /* 'x' is a very large value and the result wraps around to zero */ +new_ptr = realloc(ptr, new_size); +if (!new_ptr) { + free(ptr); +} +---- + ==== Handling Memory Allocation Errors Recovering from out-of-memory errors is often difficult or even