From 19d92fc4b86dd6f8f5f6a8152db42e5de70e2a3b Mon Sep 17 00:00:00 2001
From: James Willis <james.s.willis@durham.ac.uk>
Date: Wed, 30 Nov 2016 14:15:30 +0000
Subject: [PATCH] Free allocated memory if the cache needs to be re-allocated.

---
 src/cache.h | 12 ++++++++++++
 1 file changed, 12 insertions(+)

diff --git a/src/cache.h b/src/cache.h
index 8c13588c6c..1ca245b5a5 100644
--- a/src/cache.h
+++ b/src/cache.h
@@ -74,6 +74,18 @@ __attribute__((always_inline)) INLINE void cache_init(struct cache *c, size_t co
   unsigned int sizeBytes = (count + (2 * VEC_SIZE)) * sizeof(float);
   int error = 0;
 
+  /* Free memory if cache has already been allocated. */
+  if (c->count > 0) {
+    free(c->x);
+    free(c->y);
+    free(c->z);
+    free(c->m);
+    free(c->vx);
+    free(c->vy);
+    free(c->vz);
+    free(c->h);
+  }
+
   error += posix_memalign((void **)&c->x, alignment,sizeBytes);
   error += posix_memalign((void **)&c->y, alignment,sizeBytes);
   error += posix_memalign((void **)&c->z, alignment,sizeBytes);
-- 
GitLab