From caa5af94fe9f3a1dab6deecc8c646eccd58338c7 Mon Sep 17 00:00:00 2001
From: Max Mouratov <mmouratov@gmail.com>
Date: Sun, 21 Oct 2012 20:39:17 +0600
Subject: [PATCH] Fix: VirtualAlloc leaks when freeing the heap on win32

---
 os_dep.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/os_dep.c b/os_dep.c
index da0f24d7..7efa0871 100644
--- a/os_dep.c
+++ b/os_dep.c
@@ -2259,7 +2259,14 @@ void * os2_alloc(size_t bytes)
 #       endif
         GC_heap_bases[GC_n_heap_bases] = 0;
       }
-    }
+
+    // Avoiding the VirtualAlloc leak
+    } else {
+        while (GC_n_heap_bases > 0) {
+          VirtualFree(GC_heap_bases[--GC_n_heap_bases], 0, MEM_RELEASE);
+          GC_heap_bases[GC_n_heap_bases] = 0;
+        }
+      }
   }
 #endif /* MSWIN32 || CYGWIN32 */
 
-- 
2.40.0