From 898e9a87dfc1b74d9459cc7079f7df66bc2ca07c Mon Sep 17 00:00:00 2001 From: Michael Kerrisk Date: Tue, 14 Dec 2004 18:25:46 +0000 Subject: [PATCH] Hello Joey, http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=205736 [[ This example contains the following line: if ((p = realloc (p, size)) == NULL) return NULL; This is a very ill written code, since realloc returning NULL do not deallocate the original memory block. Such a statement has a potential to become significant memory hole. I suggest to correct this example since: 1. It may trick naive programmers to write bad code 2. It may lead skeptic observers to the believe the whole Linux is written in a similar style. Regards Jan Kuznik ]] This guy is right on the money! I've changed that example, so that the above code has been replaced by: char *np; ... if ((np = realloc (p, size)) == NULL) { free(p); return NULL; } else { p = np; } Cheers, Michael --- man3/printf.3 | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/man3/printf.3 b/man3/printf.3 index a5daac871..f96630a37 100644 --- a/man3/printf.3 +++ b/man3/printf.3 @@ -756,14 +756,17 @@ To allocate a sufficiently large string and print into it #include #include #include + char * make_message(const char *fmt, ...) { /* Guess we need no more than 100 bytes. */ int n, size = 100; - char *p; + char *p, *np; va_list ap; + if ((p = malloc (size)) == NULL) return NULL; + while (1) { /* Try to print in the allocated space. */ va_start(ap, fmt); @@ -777,8 +780,12 @@ make_message(const char *fmt, ...) { size = n+1; /* precisely what is needed */ else /* glibc 2.0 */ size *= 2; /* twice the old size */ - if ((p = realloc (p, size)) == NULL) + if ((np = realloc (p, size)) == NULL) { + free(p); return NULL; + } else { + p = np; + } } } .fi