From e9d9f7b01bc45fcfcf13b712651cf2a477bda7a0 Mon Sep 17 00:00:00 2001
From: Ivica Ico Bukvic <ico@vt.edu>
Date: Sun, 11 Dec 2011 13:03:12 -0500
Subject: [PATCH] fixed memory leak for invisible 2 canvases with templates.
 they are now being freed when closing pd as they should be.

---
 src/g_array.c |  6 ++++--
 src/s_inter.c | 26 ++++++--------------------
 2 files changed, 10 insertions(+), 22 deletions(-)

diff --git a/src/g_array.c b/src/g_array.c
index bafe8ac07..b3e5fed10 100644
--- a/src/g_array.c
+++ b/src/g_array.c
@@ -138,7 +138,8 @@ struct _garray
 	t_symbol *x_send;		/* send_changed hook */
 };
 
-static t_pd *garray_arraytemplatecanvas;
+t_pd *garray_arraytemplatecanvas;
+t_pd *garray_floattemplatecanvas;
 static char garray_arraytemplatefile[] = "\
 #N canvas 0 0 458 153 10;\n\
 #X obj 43 31 struct _float_array array z float float style\n\
@@ -163,6 +164,7 @@ void garray_init( void)
     glob_setfilename(0, gensym("_float"), gensym("."));
     binbuf_text(b, garray_floattemplatefile, strlen(garray_floattemplatefile));
     binbuf_eval(b, 0, 0, 0);
+    garray_floattemplatecanvas = s__X.s_thing;
     vmess(s__X.s_thing, gensym("pop"), "i", 0);
     
     glob_setfilename(0, gensym("_float_array"), gensym("."));
@@ -172,7 +174,7 @@ void garray_init( void)
     vmess(s__X.s_thing, gensym("pop"), "i", 0);
 
     glob_setfilename(0, &s_, &s_);
-    binbuf_free(b);  
+    binbuf_free(b);
 }
 
 /* create a new scalar attached to a symbol.  Used to make floating-point
diff --git a/src/s_inter.c b/src/s_inter.c
index d2226f3e6..1cf70a6ae 100644
--- a/src/s_inter.c
+++ b/src/s_inter.c
@@ -1311,28 +1311,14 @@ void sys_bail(int n)
     else _exit(1);
 }
 
+extern t_pd *garray_arraytemplatecanvas;
+extern t_pd *garray_floattemplatecanvas;
+
 void glob_quit(void *dummy)
 {
-	/* deallocate rendundant memory (see g_canvas.c canvas_new and g_canvas.h for struct declaration */
-/*
-	if (rm_start) {
-		while (rm_start->rm_next) {
-			t_redundant_mem *tmp = rm_start;
-			rm_start = rm_start->rm_next;
-			// 	we can also explicitly look for deallocating per-canvas settings here, if such proves necessary 
-			//	to do so, look at rm_start->rm_canvas
-
-			//fprintf(stderr,".x%lx\n", tmp->rm_canvas);
-			t_freebytes(tmp,  sizeof(*tmp));
-			//fprintf(stderr,"dealloc\n");
-		}
-		if (rm_start) {
-			t_freebytes(rm_start,  sizeof(*rm_start));
-			//fprintf(stderr,"last dealloc\n");
-		}
-	}
-*/
-
+	//let's try to cleanly remove invisible template canvases to avoid memory leaks
+	if (garray_arraytemplatecanvas) canvas_free( (t_canvas *)garray_arraytemplatecanvas);
+	if (garray_floattemplatecanvas) canvas_free( (t_canvas *)garray_floattemplatecanvas);
     sys_vgui("exit\n");
     if (!sys_nogui)
     {
-- 
GitLab