From f4094214ebc8ef7c5e8140605bc17907b5672b13 Mon Sep 17 00:00:00 2001 From: Jonathan Neuschäfer Date: Mon, 15 Aug 2011 22:10:07 +0200 Subject: fix a realloc-related memory leak in localhost() * libshouldbeinlibc/localhost.c (localhost): assign the return value of realloc to a temporary variable to avoid losing the old value of buf in the case of realloc failing. --- libshouldbeinlibc/localhost.c | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) (limited to 'libshouldbeinlibc/localhost.c') diff --git a/libshouldbeinlibc/localhost.c b/libshouldbeinlibc/localhost.c index f0c67541..f21f970d 100644 --- a/libshouldbeinlibc/localhost.c +++ b/libshouldbeinlibc/localhost.c @@ -39,18 +39,25 @@ localhost () errno = 0; if (buf) { + char *new; buf_len += buf_len; - buf = realloc (buf, buf_len); + new = realloc (buf, buf_len); + if (! new) + { + errno = ENOMEM; + return 0; + } + else + buf = new; } else { buf_len = 128; /* Initial guess */ buf = malloc (buf_len); + if (! buf) + { + errno = ENOMEM; + return 0; + } } - - if (! buf) - { - errno = ENOMEM; - return 0; - } } while ((gethostname(buf, buf_len) == 0 && !memchr (buf, '\0', buf_len)) || errno == ENAMETOOLONG); -- cgit v1.2.3 From 35b2f0e44af1544253e0d1d5edaf5afe6d879f97 Mon Sep 17 00:00:00 2001 From: Samuel Thibault Date: Sat, 20 Aug 2011 18:30:28 +0200 Subject: Fix localhost() after memory failure * libshouldbeinlibc/localhost.c (localhost): Free and reset buf when reallocation failed. --- libshouldbeinlibc/localhost.c | 2 ++ 1 file changed, 2 insertions(+) (limited to 'libshouldbeinlibc/localhost.c') diff --git a/libshouldbeinlibc/localhost.c b/libshouldbeinlibc/localhost.c index f21f970d..f0225116 100644 --- a/libshouldbeinlibc/localhost.c +++ b/libshouldbeinlibc/localhost.c @@ -44,6 +44,8 @@ localhost () new = realloc (buf, buf_len); if (! new) { + free (buf); + buf = 0; errno = ENOMEM; return 0; } -- cgit v1.2.3