From a61bd49620d31d947dbeaf8f7ae95f9f04e720f2 Mon Sep 17 00:00:00 2001 From: Joe Finney Date: Thu, 17 Sep 2015 23:16:40 +0100 Subject: [PATCH] microbit: BUGFIX: Memory leak in ManagedType.h Corrected corner case memory leak. Instances of ManagedType<> created using the default constructor would create a reference counter by default, with a value of 0. However, if destructor or copy-assigned in this state, this reference count would not be destroyed, resulting in a 4 byte leak on the heap for each occurence. --- inc/ManagedType.h | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/inc/ManagedType.h b/inc/ManagedType.h index ad28fbd..b43a511 100644 --- a/inc/ManagedType.h +++ b/inc/ManagedType.h @@ -136,7 +136,16 @@ ManagedType::ManagedType(const ManagedType &t) template ManagedType::~ManagedType() { - if (--(*ref) == 0) + // Special case - we were created using a default constructor, and never assigned a value. + if (*ref == 0) + { + // Simply destroy our reference counter and we're done. + free(ref); + } + + // Normal case - we have a valid piece of data. + // Decrement our reference counter and free all allocated memory if we're deleting the last reference. + else if (--(*ref) == 0) { delete object; free(ref); @@ -152,7 +161,14 @@ ManagedType& ManagedType::operator = (const ManagedType&t) if (this == &t) return *this; - if (--(*ref) == 0) + // Special case - we were created using a default constructor, and never assigned a value. + if (*ref == 0) + { + // Simply destroy our reference counter, as we're about to adopt another. + free(ref); + } + + else if (--(*ref) == 0) { delete object; free(ref);