From 353922fd3bb3d8296735fb8cd865d3722778847b Mon Sep 17 00:00:00 2001
From: Allanis <allanis@saracraft.net>
Date: Wed, 20 Mar 2013 22:39:38 +0000
Subject: [PATCH] [Fix] Outstanding memory write access issue.

---
 src/toolkit.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)

diff --git a/src/toolkit.c b/src/toolkit.c
index cd771fa..3919018 100644
--- a/src/toolkit.c
+++ b/src/toolkit.c
@@ -278,7 +278,8 @@ void window_addCust(const unsigned int wid, const int x, const int y,
 static Widget* window_newWidget(Window* w) {
   Widget* wgt = NULL;
 
-  w->widgets = realloc(w->widgets, sizeof(Widget)*(++w->nwidgets));
+	w->nwidgets++;
+  w->widgets = realloc(w->widgets, sizeof(Widget)*w->nwidgets);
   if(w->widgets == NULL) WARN("Out of memory");
 
   wgt = &w->widgets[w->nwidgets - 1];
@@ -885,7 +886,7 @@ static void toolkit_mouseEvent(SDL_Event* event) {
   int i;
   double x, y;
   Window* w;
-  Widget* wgt;
+  Widget* wgt, *wgt_func;
 
   // Set mouse button status.
   if(event->type == SDL_MOUSEBUTTONDOWN) mouse_down = 1;
@@ -912,6 +913,7 @@ static void toolkit_mouseEvent(SDL_Event* event) {
   x -= w->x;
   y -= w->y;
 
+	wgt_func = NULL;
   for(i = 0; i < w->nwidgets; i++) {
     wgt = &w->widgets[i];
 		// Widget in range?
@@ -943,7 +945,8 @@ static void toolkit_mouseEvent(SDL_Event* event) {
 									DEBUG("Toolkit: Button '%s' of Window '%s'"
 												"Does not have a function trigger",
 												wgt->name, w->name);
-								else (*wgt->dat.btn.fptr)(wgt->name);
+								else
+									wgt_func = wgt; // Run it at the end in case of close.
 							}
           	}
           	wgt->status = WIDGET_STATUS_NORMAL;
@@ -956,6 +959,7 @@ static void toolkit_mouseEvent(SDL_Event* event) {
 		else if(!mouse_down)
     	wgt->status = WIDGET_STATUS_NORMAL;
   }
+	if(wgt_func) (*wgt_func->dat.btn.fptr)(wgt_func->name);
 }
 
 // Handle the key events.