From e019296ab7d0206dc6bc137a398b3f7f5c15f733 Mon Sep 17 00:00:00 2001
From: Simon Butcher <simon.butcher@arm.com>
Date: Wed, 12 Oct 2016 23:07:30 +0100
Subject: [PATCH] Fix stdio redirection memory leak in test suites

---
 tests/suites/helpers.function   | 5 +++++
 tests/suites/main_test.function | 7 ++++++-
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/tests/suites/helpers.function b/tests/suites/helpers.function
index 5938447af..ff3ab99e4 100644
--- a/tests/suites/helpers.function
+++ b/tests/suites/helpers.function
@@ -140,6 +140,11 @@ static int restore_output( FILE** out_stream, int old_fd )
 
     return 0;
 }
+
+static void close_output( FILE* stdout )
+{
+    fclose( stdout );
+}
 #endif /* __unix__ || __APPLE__ __MACH__ */
 
 static int unhexify( unsigned char *obuf, const char *ibuf )
diff --git a/tests/suites/main_test.function b/tests/suites/main_test.function
index 14209a576..afff5a482 100644
--- a/tests/suites/main_test.function
+++ b/tests/suites/main_test.function
@@ -261,7 +261,7 @@ int main(int argc, const char *argv[])
     char buf[5000];
     char *params[50];
     void *pointer;
-    int stdout_fd = 0;
+    int stdout_fd = -1;
 
 #if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && \
     !defined(TEST_SUITE_MEMORY_BUFFER_ALLOC)
@@ -499,6 +499,11 @@ int main(int argc, const char *argv[])
     mbedtls_memory_buffer_alloc_free();
 #endif
 
+#if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
+    if( stdout_fd != -1 )
+        close_output( stdout );
+#endif /* __unix__ || __APPLE__ __MACH__ */
+
     return( total_errors != 0 );
 }