[pan: 14/15] Fix embarrassing access to freed memory




commit 7b78a241a64c411d4e62aa1915737d49c121be65
Author: Thomas Tanner <thosrtanner googlemail com>
Date:   Sat Jun 11 18:29:05 2022 +0100

    Fix embarrassing access to freed memory

 pan/gui/gui.cc     | 29 +++++++++++++++++++++++++++--
 pan/gui/post-ui.cc |  2 ++
 2 files changed, 29 insertions(+), 2 deletions(-)
---
diff --git a/pan/gui/gui.cc b/pan/gui/gui.cc
index 47e4260..55110ad 100644
--- a/pan/gui/gui.cc
+++ b/pan/gui/gui.cc
@@ -2372,6 +2372,29 @@ GUI :: on_prefs_string_changed (const StringView& key, const StringView& value)
   }
 }
 
+namespace {
+class Destroyer {
+  public:
+    Destroyer(char *f) :
+      _fname(f)
+    {
+    }
+
+    ~Destroyer()
+    {
+      g_free(_fname);
+    }
+
+    void retain()
+    {
+      _fname = nullptr;
+    }
+
+  private:
+    char *_fname;
+};
+}
+
 void
 GUI :: do_edit_scores (GtkAction *act)
 {
@@ -2380,8 +2403,8 @@ GUI :: do_edit_scores (GtkAction *act)
     return;
   }
 
-  //This isn't lovely. But I know I don't free filename in the callback
-  char *filename = const_cast<char *>(_data.get_scorefile_name().c_str());
+  char *filename{g_strdup(_data.get_scorefile_name().c_str())};
+  Destroyer d{filename};
   if (not file::file_exists(filename)) {
     FILE *f = fopen(filename, "a+");
     if (f == nullptr) {
@@ -2398,6 +2421,7 @@ GUI :: do_edit_scores (GtkAction *act)
       new EditorSpawner(filename,
                         std::bind(&GUI::edit_scores_cleanup, this, _1, _2, act),
                         _prefs));
+    d.retain();
     gtk_action_set_sensitive(act, false);
   }
   catch (EditorSpawnerError const &)
@@ -2409,6 +2433,7 @@ GUI :: do_edit_scores (GtkAction *act)
 void
 GUI :: edit_scores_cleanup(int status, char *filename, GtkAction *act)
 {
+  g_free(filename);
   _data.rescore();
   gtk_action_set_sensitive(act, true);
   _spawner.reset();
diff --git a/pan/gui/post-ui.cc b/pan/gui/post-ui.cc
index 238b2c2..6cd9902 100644
--- a/pan/gui/post-ui.cc
+++ b/pan/gui/post-ui.cc
@@ -1312,6 +1312,7 @@ PostUI :: maybe_post_message (GMimeMessage * message)
 ****
 ***/
 
+namespace {
 class Destroyer {
   public:
     Destroyer(char *f) :
@@ -1332,6 +1333,7 @@ class Destroyer {
   private:
     char *_fname;
 };
+}
 
 void
 PostUI :: spawn_editor ()


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]