[dia] general: prefer g_clear_* over g_free/g_object_unref



commit 01875468b9c21cbc22b50668be8ca37d2302037d
Author: Zander Brown <zbrown gnome org>
Date:   Fri Apr 3 22:17:15 2020 +0100

    general: prefer g_clear_* over g_free/g_object_unref
    
    The g_clear_* macros are safe to use on NULL pointers and null out
    pointers
    
    This helps avoid using bad pointers but is mostly stylistic

 app/app_procs.c                            |  49 ++--
 app/commands.c                             |  52 ++--
 app/confirm.c                              |   8 +-
 app/create_object.c                        |  13 +-
 app/defaults.c                             |  13 +-
 app/dia-guide-tool.c                       |  10 +-
 app/dia-props.c                            |   4 +-
 app/dia-win-remote.c                       |  74 ++---
 app/diagram.c                              |  24 +-
 app/diagram_tree_model.c                   |  82 ++++--
 app/diagram_tree_view.c                    | 140 ++++++----
 app/disp_callbacks.c                       |  34 ++-
 app/display.c                              |  75 +++--
 app/exit_dialog.c                          | 200 +++++++-------
 app/exit_dialog.h                          |  20 +-
 app/filedlg.c                              | 148 +++++-----
 app/find-and-replace.c                     |  35 ++-
 app/interface.c                            |  17 +-
 app/layer-editor/dia-layer-editor-dialog.c |   2 +-
 app/layer-editor/layer_dialog.c            |   2 +-
 app/load_save.c                            |  54 ++--
 app/magnify.c                              |   7 +-
 app/menus.c                                |  89 +++---
 app/modify_tool.c                          |  19 +-
 app/navigation.c                           |  13 +-
 app/object_ops.c                           |   8 +-
 app/pagesetup.c                            |  29 +-
 app/properties-dialog.c                    |  10 +-
 app/recent_files.c                         |  69 +++--
 app/ruler.c                                |  13 +-
 app/scroll_tool.c                          |   9 +-
 app/sheet-editor/sheets.c                  |  19 +-
 app/sheet-editor/sheets_dialog.c           |   8 +-
 app/sheet-editor/sheets_dialog_callbacks.c |  30 +-
 app/textedit_tool.c                        |   3 +-
 app/toolbox.c                              |  94 ++++---
 app/undo.c                                 |  26 +-
 app/winmain.c                              |  18 +-
 lib/arrows.c                               |   2 +-
 lib/autoroute.c                            |  10 +-
 lib/bezier_conn.c                          |  27 +-
 lib/beziershape.c                          |  35 +--
 lib/boundingbox.c                          |   9 +-
 lib/color.c                                |   2 +-
 lib/connpoint_line.c                       | 164 ++++++-----
 lib/create.c                               |   2 +-
 lib/dia-guide.c                            |   2 +-
 lib/dia_dirs.c                             |  40 +--
 lib/dia_image.c                            |  56 ++--
 lib/dia_svg.c                              |  81 +++---
 lib/dia_xml.c                              | 215 +++++++++------
 lib/diaarrowchooser.c                      |   2 +-
 lib/diacolorselector.c                     |   7 +-
 lib/diacontext.c                           |  58 ++--
 lib/diafontselector.c                      |  16 +-
 lib/diagramdata.c                          |  25 +-
 lib/diaimportrenderer.c                    |   6 +-
 lib/dialib.c                               |  28 +-
 lib/diapathrenderer.c                      |   2 +-
 lib/diapatternselector.c                   |  45 +--
 lib/diarenderer.c                          |  13 +-
 lib/diasvgrenderer.c                       |  19 +-
 lib/diatransformrenderer.c                 |   5 +-
 lib/dynamic_obj.c                          |  26 +-
 lib/font-height.c                          |  30 +-
 lib/font.c                                 |  65 +++--
 lib/group.c                                |  27 +-
 lib/layer.c                                |   7 +-
 lib/message.c                              |  48 ++--
 lib/objchange.c                            |  32 ++-
 lib/object.c                               |  28 +-
 lib/object_defaults.c                      |  34 +--
 lib/orth_conn.c                            |  43 ++-
 lib/parent.c                               |  27 +-
 lib/persistence.c                          |  47 ++--
 lib/plug-ins.c                             |  42 +--
 lib/poly_conn.c                            |  13 +-
 lib/polyshape.c                            |  21 +-
 lib/prop_attr.c                            |  12 +-
 lib/prop_basic.c                           |  12 +-
 lib/prop_dict.c                            |   2 +-
 lib/prop_geomtypes.c                       |  66 +++--
 lib/prop_inttypes.c                        |  84 +++---
 lib/prop_matrix.c                          |  13 +-
 lib/prop_pattern.c                         |  67 +++--
 lib/prop_pixbuf.c                          | 106 ++++----
 lib/prop_sdarray.c                         |   2 +-
 lib/prop_sdarray_widget.c                  |  35 +--
 lib/prop_text.c                            |  44 +--
 lib/prop_widgets.c                         |   6 +-
 lib/propdesc.c                             |   6 +-
 lib/properties.h                           |   2 +-
 lib/proplist.c                             |  41 ++-
 lib/propobject.c                           |  12 +-
 lib/renderer/diacairo-interactive.c        |   4 +-
 lib/renderer/diacairo-print.c              |  26 +-
 lib/renderer/diacairo-renderer.c           |  17 +-
 lib/renderer/diacairo.c                    |  14 +-
 lib/sheet.c                                |  77 +++---
 lib/standard-path.c                        |  17 +-
 lib/text.c                                 |  76 +++---
 lib/textline.c                             |  28 +-
 lib/widgets.c                              |  86 +++---
 objects/AADL/aadlbox.c                     |  15 +-
 objects/AADL/edit_port_declaration.c       |   4 +-
 objects/Database/compound.c                |   8 +-
 objects/Database/reference.c               |   6 +-
 objects/Database/table.c                   | 166 +++++------
 objects/ER/attribute.c                     |   2 +-
 objects/ER/entity.c                        |   4 +-
 objects/ER/participation.c                 |   6 +-
 objects/ER/relationship.c                  |   8 +-
 objects/FS/flow-ortho.c                    |   4 +-
 objects/FS/function.c                      |  10 +-
 objects/GRAFCET/boolequation.c             |  77 ++++--
 objects/GRAFCET/boolequation.h             |   2 +-
 objects/GRAFCET/condition.c                |   6 +-
 objects/GRAFCET/step.c                     |   2 +-
 objects/GRAFCET/transition.c               |   2 +-
 objects/Istar/link.c                       |   4 +-
 objects/Jackson/phenomenon.c               |   8 +-
 objects/KAOS/metaandorrel.c                |  10 +-
 objects/KAOS/metabinrel.c                  |  13 +-
 objects/Misc/diagram_as_object.c           |  46 ++--
 objects/Misc/grid_object.c                 |   4 +-
 objects/Misc/measure.c                     |   2 +-
 objects/Misc/n_gon.c                       |  11 +-
 objects/Misc/tree.c                        |  20 +-
 objects/SADT/box.c                         |   2 +-
 objects/UML/association.c                  |  80 +++---
 objects/UML/class.c                        | 108 ++++----
 objects/UML/class_attributes_dialog.c      |   2 +-
 objects/UML/class_dialog.c                 |  46 ++--
 objects/UML/class_operations_dialog.c      |   6 +-
 objects/UML/component.c                    |   7 +-
 objects/UML/constraint.c                   |   9 +-
 objects/UML/dependency.c                   |  28 +-
 objects/UML/generalization.c               |  29 +-
 objects/UML/implements.c                   |   2 +-
 objects/UML/large_package.c                |  22 +-
 objects/UML/lifeline.c                     |  14 +-
 objects/UML/message.c                      |  13 +-
 objects/UML/object.c                       |  36 +--
 objects/UML/realizes.c                     |  27 +-
 objects/UML/small_package.c                |  30 +-
 objects/UML/state.c                        |  52 ++--
 objects/UML/stereotype.c                   |  56 ++--
 objects/UML/transition.c                   |  44 ++-
 objects/UML/umlattribute.c                 |  12 +-
 objects/UML/umlformalparameter.c           |   4 +-
 objects/UML/umloperation.c                 |  49 +---
 objects/chronogram/chronoline.c            |   4 +-
 objects/chronogram/chronoline_event.c      |   8 +-
 objects/custom/custom.c                    |  84 +++---
 objects/custom/custom_object.c             |  66 +++--
 objects/custom/custom_util.c               |  19 +-
 objects/custom/shape_info.c                | 101 +++----
 objects/custom/shape_typeinfo.c            |  30 +-
 objects/custom_lines/custom_lines.c        |  66 ++---
 objects/custom_lines/line_info.c           |   6 +-
 objects/network/bus.c                      |  15 +-
 objects/standard/arc.c                     |   3 +-
 objects/standard/bezier.c                  |   3 +-
 objects/standard/beziergon.c               |  10 +-
 objects/standard/box.c                     |   7 +-
 objects/standard/ellipse.c                 |   7 +-
 objects/standard/image.c                   |  57 ++--
 objects/standard/outline.c                 |   2 +-
 objects/standard/polygon.c                 |   7 +-
 objects/standard/textobj.c                 |   3 +-
 objects/standard/zigzagline.c              |   2 +-
 plug-ins/cgm/cgm.c                         |  10 +-
 plug-ins/drs/dia-render-script-import.c    |  10 +-
 plug-ins/drs/dia-render-script-renderer.c  |  20 +-
 plug-ins/drs/dia-render-script.c           |   8 +-
 plug-ins/dxf/dxf-export.c                  |   7 +-
 plug-ins/dxf/dxf-import.c                  |  83 +++---
 plug-ins/hpgl/hpgl.c                       |   6 +-
 plug-ins/metapost/render_metapost.c        |  27 +-
 plug-ins/pgf/render_pgf.c                  |   8 +-
 plug-ins/pixbuf/pixbuf.c                   |  48 ++--
 plug-ins/postscript/diapsrenderer.c        |  10 +-
 plug-ins/postscript/paginate_psprint.c     |  35 +--
 plug-ins/postscript/ps-utf8.c              | 129 ++++-----
 plug-ins/postscript/ps-utf8.h              |  52 ++--
 plug-ins/postscript/render_eps.c           |  23 +-
 plug-ins/pstricks/render_pstricks.c        | 166 +++++------
 plug-ins/python/diamodule.c                |   4 +-
 plug-ins/python/pydia-color.c              |  36 ++-
 plug-ins/python/pydia-diagram.c            |  25 +-
 plug-ins/python/pydia-diagramdata.c        |  67 +++--
 plug-ins/python/pydia-error.c              |   2 +-
 plug-ins/python/pydia-font.c               |  16 +-
 plug-ins/python/pydia-geometry.c           | 265 ++++++++++--------
 plug-ins/python/pydia-image.c              | 113 ++++----
 plug-ins/python/pydia-layer.c              |   2 +-
 plug-ins/python/pydia-menuitem.c           |  30 +-
 plug-ins/python/pydia-object.c             | 200 ++++++++------
 plug-ins/python/pydia-paperinfo.c          |  32 ++-
 plug-ins/python/pydia-properties.c         |   8 +-
 plug-ins/python/pydia-property.c           | 138 ++++++----
 plug-ins/python/pydia-render.c             | 104 +++----
 plug-ins/python/pydia-text.c               |  22 +-
 plug-ins/python/python.c                   | 163 ++++++-----
 plug-ins/shape/shape-export.c              |  47 ++--
 plug-ins/svg/render_svg.c                  |  51 ++--
 plug-ins/svg/svg-import.c                  | 423 +++++++++++++++--------------
 plug-ins/vdx/vdx-export.c                  |  77 +++---
 plug-ins/vdx/vdx-import.c                  |  93 +++----
 plug-ins/wpg/wpg-import.c                  |  36 ++-
 plug-ins/wpg/wpg.c                         |  16 +-
 plug-ins/xfig/xfig-export.c                |  37 +--
 plug-ins/xfig/xfig-import.c                |  31 ++-
 plug-ins/xslt/xslt.c                       |  21 +-
 tests/test-boundingbox.c                   |  15 +-
 tests/test-objects.c                       |  48 ++--
 tests/test-svg.c                           |  21 +-
 217 files changed, 4356 insertions(+), 3783 deletions(-)
---
diff --git a/app/app_procs.c b/app/app_procs.c
index 3b690b04..b5b37b4c 100644
--- a/app/app_procs.c
+++ b/app/app_procs.c
@@ -102,11 +102,15 @@ build_output_file_name(const char *infname, const char *format, const char *outd
   memcpy(tmp,pp,pe-pp);
   strcat(tmp,".");
   strcat(tmp,format);
+
   if (outdir) {
     char *ret = g_strconcat(outdir, G_DIR_SEPARATOR_S, tmp, NULL);
-    g_free(tmp);
+
+    g_clear_pointer (&tmp, g_free);
+
     return ret;
   }
+
   return tmp;
 }
 
@@ -280,7 +284,7 @@ handle_show_layers (DiagramData *diagdata,
       dia_layer_set_visible (layer, FALSE);
     }
   }
-  g_free(visible_layers);
+  g_clear_pointer (&visible_layers, g_free);
 }
 
 
@@ -353,7 +357,7 @@ do_convert (const char      *infname,
   }
   /* if (!quiet) */
   g_printerr (_("%s --> %s\n"), infname, outfname);
-  g_object_unref (diagdata);
+  g_clear_object (&diagdata);
   dia_context_release (ctx);
   return TRUE;
 }
@@ -457,7 +461,7 @@ handle_initial_diagram (const char *in_file_name,
                     export_file_format);
         return FALSE;
       }
-      g_free (export_file_name);
+      g_clear_pointer (&export_file_name, g_free);
       export_file_name = build_output_file_name (in_file_name,
                                                  ef->extensions[0],
                                                  outdir);
@@ -467,7 +471,7 @@ handle_initial_diagram (const char *in_file_name,
                                     ef,
                                     size,
                                     show_layers);
-    g_free (export_file_name);
+    g_clear_pointer (&export_file_name, g_free);
   } else if (out_file_name) {
     DiaExportFilter *ef = NULL;
     made_conversions |= do_convert (in_file_name,
@@ -493,7 +497,7 @@ handle_initial_diagram (const char *in_file_name,
         /* the display initial diagram holds two references */
         new_display (diagram);
       } else {
-        g_object_unref (diagram);
+        g_clear_object (&diagram);
       }
     }
   }
@@ -510,6 +514,7 @@ handle_initial_diagram (const char *in_file_name,
 static const gchar *input_directory = NULL;
 static const gchar *output_directory = NULL;
 
+
 static gboolean
 _check_option_input_directory (const gchar    *option_name,
                                const gchar    *value,
@@ -524,9 +529,11 @@ _check_option_input_directory (const gchar    *option_name,
   }
   g_set_error (error, DIA_ERROR, DIA_ERROR_DIRECTORY,
                _("Input directory '%s' must exist!\n"), directory);
-  g_free (directory);
+  g_clear_pointer (&directory, g_free);
   return FALSE;
 }
+
+
 static gboolean
 _check_option_output_directory (const gchar    *option_name,
                                 const gchar    *value,
@@ -541,7 +548,7 @@ _check_option_output_directory (const gchar    *option_name,
   }
   g_set_error (error, DIA_ERROR, DIA_ERROR_DIRECTORY,
                _("Output directory '%s' must exist!\n"), directory);
-  g_free (directory);
+  g_clear_pointer (&directory, g_free);
   return FALSE;
 }
 
@@ -631,7 +638,7 @@ app_init (int argc, char **argv)
     if (!g_option_context_parse (context, &argc, &argv, &error)) {
       if (error) { /* IMO !error here is a bug upstream, triggered e.g. with --gdk-debug=updates */
         g_printerr ("%s", error->message);
-        g_error_free (error);
+        g_clear_error (&error);
       } else {
         g_printerr (_("Invalid option?"));
       }
@@ -650,7 +657,7 @@ app_init (int argc, char **argv)
           if (!g_utf8_validate (filename, -1, NULL)) {
             gchar *tfn = filename;
             filename = g_filename_to_utf8 (filename, -1, NULL, NULL, NULL);
-            g_free (tfn);
+            g_clear_pointer (&tfn, g_free);
           }
         } else {
           filename = g_filename_to_utf8 (filenames[i], -1, NULL, NULL, NULL);
@@ -673,10 +680,10 @@ app_init (int argc, char **argv)
           files = g_slist_append (files, filename);
         } else {
           g_printerr (_("Missing input: %s\n"), filename);
-          g_free (filename);
+          g_clear_pointer (&filename, g_free);
         }
         if (filename != testpath) {
-          g_free (testpath);
+          g_clear_pointer (&testpath, g_free);
         }
         ++i;
       }
@@ -703,7 +710,7 @@ app_init (int argc, char **argv)
     pixbuf = pixbuf_from_resource ("/org/gnome/Dia/icons/org.gnome.Dia.png");
     if (pixbuf) {
       gtk_window_set_default_icon (pixbuf);
-      g_object_unref (pixbuf);
+      g_clear_object (&pixbuf);
     }
   } else {
     /*
@@ -727,8 +734,8 @@ app_init (int argc, char **argv)
 #endif
     ver_locale = g_locale_from_utf8 (ver_utf8, -1, NULL, NULL, NULL);
     printf ("%s\n", ver_locale);
-    g_free (ver_locale);
-    g_free (ver_utf8);
+    g_clear_pointer (&ver_locale, g_free);
+    g_clear_pointer (&ver_utf8, g_free);
     if (verbose) {
       dump_dependencies ();
     }
@@ -921,7 +928,7 @@ app_exit (void)
           } else {
             dia_context_reset (ctx);
           }
-          g_free (filename);
+          g_clear_pointer (&filename, g_free);
         }
         dia_context_release (ctx);
         exit_dialog_free_items (items);
@@ -1040,15 +1047,15 @@ create_user_dirs (void)
   /* it is no big deal if these directories can't be created */
   subdir = g_strconcat (dir, G_DIR_SEPARATOR_S "objects", NULL);
   g_mkdir (subdir, 0755);
-  g_free (subdir);
+  g_clear_pointer (&subdir, g_free);
   subdir = g_strconcat (dir, G_DIR_SEPARATOR_S "shapes", NULL);
   g_mkdir (subdir, 0755);
-  g_free (subdir);
+  g_clear_pointer (&subdir, g_free);
   subdir = g_strconcat (dir, G_DIR_SEPARATOR_S "sheets", NULL);
   g_mkdir (subdir, 0755);
-  g_free (subdir);
+  g_clear_pointer (&subdir, g_free);
 
-  g_free (dir);
+  g_clear_pointer (&dir, g_free);
 }
 
 static PluginInitResult
@@ -1097,7 +1104,7 @@ handle_all_diagrams (GSList     *files,
                               show_layers,
                               output_dir);
     if (inpath != node->data) {
-      g_free (inpath);
+      g_clear_pointer (&inpath, g_free);
     }
   }
   return made_conversions;
diff --git a/app/commands.c b/app/commands.c
index 78e0a8f9..dcedd5a9 100644
--- a/app/commands.c
+++ b/app/commands.c
@@ -168,7 +168,7 @@ file_new_callback (GtkAction *action)
 
   new_display (dia);
 
-  g_free (name);
+  g_clear_pointer (&name, g_free);
   g_clear_object (&file);
 }
 
@@ -312,7 +312,7 @@ received_clipboard_image_handler (GtkClipboard *clipboard,
       change = dia_object_set_pixbuf (obj, pixbuf);
       if (change) { /* ... but drop undo info */
         change->free (change);
-        g_free (change);
+        g_clear_pointer (&change, g_free);
       }
       /* allow undo of the whole thing */
       dia_insert_objects_change_new (dia, g_list_prepend (NULL, obj), 1);
@@ -380,13 +380,13 @@ received_clipboard_content_handler (GtkClipboard     *clipboard,
       GdkPixbuf *pixbuf = gtk_selection_data_get_pixbuf (selection_data);
       if (pixbuf) {
         received_clipboard_image_handler (clipboard, pixbuf, ddisp);
-        g_object_unref (pixbuf);
+        g_clear_object (&pixbuf);
       } else {
         message_error (_("Paste failed: %s"), type_name);
       }
     }
     dia_log_message ("Content is %s (size=%d)", type_name, len);
-    g_free (type_name);
+    g_clear_pointer (&type_name, g_free);
   }
 }
 
@@ -418,7 +418,7 @@ edit_paste_image_callback (GtkAction *action)
         done = TRUE;
       }
       dia_log_message ("clipboard-targets %d: %s", i, aname);
-      g_free (aname);
+      g_clear_pointer (&aname, g_free);
       if (done) {
         break;
       }
@@ -428,7 +428,7 @@ edit_paste_image_callback (GtkAction *action)
                                    received_clipboard_image_handler,
                                    ddisp);
     }
-    g_free (targets);
+    g_clear_pointer (&targets, g_free);
   }
 }
 
@@ -437,6 +437,7 @@ static PropDescription text_prop_singleton_desc[] = {
   PROP_DESC_END
 };
 
+
 static void
 make_text_prop_singleton (GPtrArray **props, TextProperty **prop)
 {
@@ -444,10 +445,10 @@ make_text_prop_singleton (GPtrArray **props, TextProperty **prop)
   g_assert ((*props)->len == 1);
 
   *prop = g_ptr_array_index ((*props),0);
-  g_free ((*prop)->text_data);
-  (*prop)->text_data = NULL;
+  g_clear_pointer (&(*prop)->text_data, g_free);
 }
 
+
 static GtkTargetEntry target_entries[] = {
   { "image/svg", GTK_TARGET_OTHER_APP, 1 },
   { "image/svg+xml", GTK_TARGET_OTHER_APP, 2 },
@@ -493,7 +494,7 @@ _clipboard_get_data_callback (GtkClipboard     *clipboard,
   } else if (g_str_has_suffix (ext, "+xml")) {
     gchar *ext2 = g_strndup (ext, strlen (ext) - 4);
     tmplate = g_strdup_printf ("dia-cb-XXXXXX.%s", ext2);
-    g_free (ext2);
+    g_clear_pointer (&ext2, g_free);
   } else {
     tmplate = g_strdup_printf ("dia-cb-XXXXXX.%s", ext);
   }
@@ -503,10 +504,9 @@ _clipboard_get_data_callback (GtkClipboard     *clipboard,
     close (fd);
   } else {
     g_warning ("%s", error->message);
-    g_error_free (error);
-    error = NULL;
+    g_clear_error (&error);
   }
-  g_free (tmplate);
+  g_clear_pointer (&tmplate, g_free);
 
   if (ef) {
     /* for png use alpha-rendering if available */
@@ -528,7 +528,7 @@ _clipboard_get_data_callback (GtkClipboard     *clipboard,
       GdkPixbuf *pixbuf = gdk_pixbuf_new_from_file (outfname, &error);
       if (pixbuf) {
         gtk_selection_data_set_pixbuf (selection_data, pixbuf);
-        g_object_unref (pixbuf);
+        g_clear_object (&pixbuf);
       }
     } else {
       struct stat st;
@@ -545,19 +545,22 @@ _clipboard_get_data_callback (GtkClipboard     *clipboard,
                                     (guint8 *)buf, st.st_size);
           }
         }
-        g_free (buf);
+        g_clear_pointer (&buf, g_free);
         fclose (f);
         g_unlink (outfname);
       }
     }
   }
+
   if (error) {
     dia_context_add_message (ctx, "%s", error->message);
-    g_error_free (error);
   }
+
+  g_clear_error (&error);
   dia_context_release (ctx);
 }
 
+
 /** GtkClipboardClearFunc */
 static void
 _clipboard_clear_data_callback (GtkClipboard *clipboard,
@@ -566,10 +569,11 @@ _clipboard_clear_data_callback (GtkClipboard *clipboard,
   DiagramData *dia = owner_or_user_data; /* todo: check it's still valid */
 
   if (dia) {
-    g_object_unref (dia);
+    g_clear_object (&dia);
   }
 }
 
+
 void
 edit_copy_callback (GtkAction *action)
 {
@@ -1034,7 +1038,7 @@ help_manual_callback (GtkAction *action)
   if (!dp) {
     message_warning (_("Could not open help directory:\n%s"),
                      error->message);
-    g_error_free (error);
+    g_clear_error (&error);
     return;
   }
 
@@ -1044,7 +1048,7 @@ help_manual_callback (GtkAction *action)
     score = intl_score_locale (dentry);
     if (score < bestscore) {
       if (helpindex) {
-        g_free(helpindex);
+        g_clear_pointer (&helpindex, g_free);
       }
 #ifdef G_OS_WIN32
       /* use HTML Help on win32 if available */
@@ -1071,7 +1075,7 @@ help_manual_callback (GtkAction *action)
     }
   }
   g_dir_close (dp);
-  g_free (helpdir);
+  g_clear_pointer (&helpdir, g_free);
   if (!helpindex) {
     message_warning (_("Could not find help directory"));
     return;
@@ -1083,10 +1087,10 @@ help_manual_callback (GtkAction *action)
 #else
   command = g_strdup_printf ("file://%s", helpindex);
   gtk_show_uri (screen, command, gtk_get_current_event_time (), NULL);
-  g_free (command);
+  g_clear_pointer (&command, g_free);
 #endif
 
-  g_free (helpindex);
+  g_clear_pointer (&helpindex, g_free);
 }
 
 void
@@ -1144,11 +1148,11 @@ help_about_callback (GtkAction *action)
                                                 ? translators : NULL,
                          "license", license,
                          NULL);
-  if (logo) {
-    g_object_unref (logo);
-  }
+
+  g_clear_object (&logo);
 }
 
+
 void
 view_zoom_in_callback (GtkAction *action)
 {
diff --git a/app/confirm.c b/app/confirm.c
index 1bbdc50b..fb3482db 100644
--- a/app/confirm.c
+++ b/app/confirm.c
@@ -86,10 +86,12 @@ confirm_export_size (Diagram *dia, GtkWindow *parent, guint flags)
                                              "Alternatively use 'Best Fit' "
                                              "to move objects/handles into the intended bounds."));
   gtk_window_set_title (GTK_WINDOW (dialog), _("Confirm Diagram Size"));
-  g_free (size);
+  g_clear_pointer (&size, g_free);
 
-  g_signal_connect(G_OBJECT (dialog), "response",
-                  G_CALLBACK(confirm_respond), NULL);
+  g_signal_connect (G_OBJECT (dialog),
+                    "response",
+                    G_CALLBACK (confirm_respond),
+                    NULL);
 
   ret = (GTK_RESPONSE_OK == gtk_dialog_run (GTK_DIALOG (dialog)));
   gtk_widget_destroy(dialog);
diff --git a/app/create_object.c b/app/create_object.c
index add9ad21..5974ef94 100644
--- a/app/create_object.c
+++ b/app/create_object.c
@@ -265,9 +265,9 @@ create_object_motion(CreateObjectTool *tool, GdkEventMotion *event,
   gtk_statusbar_pop (statusbar, context_id);
   gtk_statusbar_push (statusbar, context_id, postext);
 
-  g_free(postext);
+  g_clear_pointer (&postext, g_free);
 
-  diagram_flush(ddisp->diagram);
+  diagram_flush (ddisp->diagram);
 
   tool->last_to = to;
 
@@ -308,13 +308,16 @@ create_create_object_tool(DiaObjectType *objtype, void *user_data,
   return (Tool *) tool;
 }
 
-void free_create_object_tool(Tool *tool)
+
+void
+free_create_object_tool(Tool *tool)
 {
   CreateObjectTool *real_tool = (CreateObjectTool *)tool;
 
   if (real_tool->moving) { /* should not get here, but see bug #619246 */
     gdk_pointer_ungrab (GDK_CURRENT_TIME);
-    ddisplay_set_all_cursor(default_cursor);
+    ddisplay_set_all_cursor (default_cursor);
   }
-  g_free(tool);
+
+  g_clear_pointer (&tool, g_free);
 }
diff --git a/app/defaults.c b/app/defaults.c
index 8a5e1a58..d8cd8799 100644
--- a/app/defaults.c
+++ b/app/defaults.c
@@ -140,13 +140,12 @@ defaults_show(DiaObjectType *objtype, gpointer user_data)
   gtk_box_pack_start(GTK_BOX(dialog_vbox), defaults, TRUE, TRUE, 0);
   gtk_widget_show (defaults);
 
-  if (title)
-    {
-      gtk_window_set_title(GTK_WINDOW(dialog), title);
-      g_free(title);
-    }
-  else
-      gtk_window_set_title (GTK_WINDOW (dialog), _("Object defaults"));
+  if (title) {
+    gtk_window_set_title (GTK_WINDOW (dialog), title);
+    g_clear_pointer (&title, g_free);
+  } else {
+    gtk_window_set_title (GTK_WINDOW (dialog), _("Object defaults"));
+  }
 
   if (object_part != defaults) {
     gtk_window_resize (GTK_WINDOW(dialog), 1, 1); /* shrink to default */
diff --git a/app/dia-guide-tool.c b/app/dia-guide-tool.c
index 01ac2c1e..19be7591 100644
--- a/app/dia-guide-tool.c
+++ b/app/dia-guide-tool.c
@@ -81,12 +81,16 @@ Tool *create_guide_tool(void)
   return (Tool *)tool;
 }
 
-void free_guide_tool(Tool *tool)
+
+void
+free_guide_tool (Tool *tool)
 {
-  GuideTool *gtool = (GuideTool *)tool;
-  g_free(gtool);
+  GuideTool *gtool = (GuideTool *) tool;
+
+  g_clear_pointer (&gtool, g_free);
 }
 
+
 static void
 guide_button_release(GuideTool *tool, GdkEventButton *event,
                      DDisplay *ddisp)
diff --git a/app/dia-props.c b/app/dia-props.c
index a214cea6..d0534ac1 100644
--- a/app/dia-props.c
+++ b/app/dia-props.c
@@ -287,9 +287,9 @@ dia_diagram_properties_dialog_init (DiaDiagramPropertiesDialog *self)
   uifile = build_ui_filename ("ui/properties-dialog.ui");
   if (!gtk_builder_add_from_file (builder, uifile, &error)) {
     g_warning ("Couldn't load builder file: %s", error->message);
-    g_error_free (error);
+    g_clear_error (&error);
   }
-  g_free (uifile);
+  g_clear_pointer (&uifile, g_free);
 
   notebook = GTK_WIDGET (gtk_builder_get_object (builder, "notebook"));
   gtk_box_pack_start (GTK_BOX (dialog_vbox), notebook, TRUE, TRUE, 0);
diff --git a/app/dia-win-remote.c b/app/dia-win-remote.c
index 9b5109eb..74d78034 100644
--- a/app/dia-win-remote.c
+++ b/app/dia-win-remote.c
@@ -5,9 +5,9 @@
  * Copyright (C) 2002, 2004, 2006 Edward G. Bruck <ebruck users sourceforge net>
  * Copyright (C) 2006, 2009 , 2010 Steffen Macke <sdteffen sdteffen de>
  *
- * dia-win-remote is a program that allows the user running 2000/XP/Vista 
- * to open a dia file in an already running Dia process. If Dia 
- * isn't running, dia-win-remote will launch it and open the requested 
+ * dia-win-remote is a program that allows the user running 2000/XP/Vista
+ * to open a dia file in an already running Dia process. If Dia
+ * isn't running, dia-win-remote will launch it and open the requested
  * file(s).
  *
  * This program is free software; you can redistribute it and/or modify
@@ -28,7 +28,7 @@
 /**
  * INCLUDES:
  */
-#include <stdio.h> 
+#include <stdio.h>
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h>
 #include <shlobj.h>
@@ -75,30 +75,30 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    gszVersion, MB_ICONSTOP);
         return -1;
     }
-       
+
        szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
        if( NULL == szArglist )
        {
                MessageBox(NULL, "CommandLineToArgvW failed\n", gszVersion, MB_ICONSTOP);
                return -1;
        }
-       
+
        /**
         * Check if first argument is an executable.
         */
        filename_utf8 = g_utf16_to_utf8(szArglist[1], -1, NULL, NULL, &error);
        if(error) {
                MessageBox(NULL, "Error converting to UTF-8!", gszVersion, MB_ICONEXCLAMATION);
-               g_free(filename_utf8);
+               g_clear_pointer (&filename_utf8, g_free);
                LocalFree(szArglist);
                return -1;
        }
        filename_utf8_down = g_utf8_strdown(filename_utf8, -1);
-       g_free(filename_utf8);
+       g_clear_pointer (&filename_utf8, g_free);
        if(g_pattern_match_simple("*.exe", filename_utf8_down))
                start_at = 2;
-       g_free(filename_utf8_down);
-        
+       g_clear_pointer (&filename_utf8_down, g_free);
+
     /**
      * Can't just look for "Dia" as other languages use
      * different title text. Lets do this the hard way
@@ -114,7 +114,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
         retval = DragAndDropDia(hWnd, nArgs, szArglist, start_at);
     }
     else
-    { 
+    {
                retval = LaunchDia(nArgs, szArglist, start_at);
     }
        LocalFree(szArglist);
@@ -139,7 +139,7 @@ int LaunchDia(int nArgs, LPWSTR *szArglist, int start_at)
        GError *error = NULL;
 
     /* Read path to Dia */
-    sprintf(szDiaKey, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s", 
+    sprintf(szDiaKey, "Software\\Microsoft\\Windows\\CurrentVersion\\App Paths\\%s",
             (gUseRegVal) ? gszDiaExe : __argv[1]);
 
     if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, szDiaKey, 0, KEY_READ, &hRegData) == ERROR_SUCCESS)
@@ -160,14 +160,14 @@ int LaunchDia(int nArgs, LPWSTR *szArglist, int start_at)
             if (pEnd != NULL)
             {
                 int len = pEnd-szAppPath;
-                
+
                 /* just incase */
                 if (len > 0 && len < _MAX_PATH)
                 {
                     strncpy(szPath, szAppPath, len);
                 }
             }
-          
+
                        /**
                         * Create commandline with URIs
                         */
@@ -177,7 +177,7 @@ int LaunchDia(int nArgs, LPWSTR *szArglist, int start_at)
                                if((0 == wcsncmp(szArglist[i], L"--", 2)) && !PathFileExistsW(szArglist[i]))
                                {
                                        uri_args = g_strdup_printf("%s %s", uri_args_cpy, __argv[i]);
-                                       g_free(uri_args_cpy);
+                                       g_clear_pointer (&uri_args_cpy, g_free);
                                        uri_args_cpy = uri_args;
                                }
                                else
@@ -185,29 +185,29 @@ int LaunchDia(int nArgs, LPWSTR *szArglist, int start_at)
                                        filename_utf8 = g_utf16_to_utf8(szArglist[i], -1, NULL, NULL, &error);
                                        if(error) {
                                                MessageBox(NULL, "Error converting to UTF-8!", gszVersion, 
MB_ICONEXCLAMATION);
-                                               g_free(filename_utf8);
-                                               g_free(uri_args);
-                                               g_free(uri_args_cpy);
+                                               g_clear_pointer (&filename_utf8, g_free);
+                                               g_clear_pointer (&uri_args, g_free);
+                                               g_clear_pointer (&uri_args_cpy, g_free);
                                                return -1;
                                        }
-                                       
+
                                        filename_uri = g_filename_to_uri(filename_utf8, NULL, &error);
                                        if(error) {
                                                MessageBox(NULL, "Error converting to URI!", gszVersion, 
MB_ICONEXCLAMATION);
-                                               g_free(filename_uri);
-                                               g_free(uri_args);
-                                               g_free(uri_args_cpy);                                   
-                                               g_free(filename_utf8);
+                                               g_clear_pointer (&filename_uri, g_free);
+                                               g_clear_pointer (&uri_args, g_free);
+                                               g_clear_pointer (&uri_args_cpy, g_free);
+                                               g_clear_pointer (&filename_utf8, g_free);
                                                return -1;
                                        }
                                        else
                                        {
                                                uri_args = g_strdup_printf("%s %s", uri_args_cpy, 
filename_uri);
-                                               g_free(uri_args_cpy);
-                                               g_free(filename_uri);
+                                               g_clear_pointer (&uri_args_cpy, g_free);
+                                               g_clear_pointer (&filename_uri, g_free);
                                                uri_args_cpy = uri_args;
                                        }
-                                       g_free(filename_utf8);
+                                       g_clear_pointer (&filename_utf8, g_free);
                                }
                        }
             /**
@@ -222,8 +222,8 @@ int LaunchDia(int nArgs, LPWSTR *szArglist, int start_at)
             {
                 iRetCode = 0;
             }
-                       g_free(uri_args);
-                       g_free(uri_args_cpy);
+                       g_clear_pointer (&uri_args, g_free);
+                       g_clear_pointer (&uri_args_cpy, g_free);
         }
     }
     else
@@ -260,7 +260,7 @@ int DragAndDropDia(HWND hWnd, int nArgs, LPWSTR *szArglist, int start_at)
     /* lock the memory */
     pDropFiles = (LPDROPFILES)GlobalLock(hGlobal);
 
-    /* set offset where the file list begins */ 
+    /* set offset where the file list begins */
     pDropFiles->pFiles = sizeof(DROPFILES);
 
     /* no wide chars and drop point is in client coordinates */
@@ -302,7 +302,7 @@ int DragAndDropDia(HWND hWnd, int nArgs, LPWSTR *szArglist, int start_at)
 /**
  * Callback to enumerate all windows searching for
  * Dia as the user could be running under a different language.
- */ 
+ */
 BOOL CALLBACK FindDiaWindow(HWND hWnd, LPARAM lParam)
 {
     char szTitle[MAX_PATH + 40]; /* should be enough to find diaw.exe */
@@ -315,15 +315,15 @@ BOOL CALLBACK FindDiaWindow(HWND hWnd, LPARAM lParam)
         {
             if (stricmp(pszToken,"diaw.exe") == 0)
             {
-                /* sanity check class name */         
+                /* sanity check class name */
                 char szClass[20]; /* should be enough */
 
                 if (GetClassName(hWnd, szClass, sizeof(szClass)) != 0)
                 {
                     /* For some reason the latest revs of Dia have a hidden
-                     * window that we may be brought to the front which causes Dia 
-                     * to appear only in the tray. 
-                    */ 
+                     * window that we may be brought to the front which causes Dia
+                     * to appear only in the tray.
+                    */
                     if (IsWindowVisible(hWnd))
                     {
                         /* if ok, then stop enumerating */
@@ -339,19 +339,19 @@ BOOL CALLBACK FindDiaWindow(HWND hWnd, LPARAM lParam)
             pszToken = strtok(NULL, " ");
         }
     }
-     
+
     return TRUE;
 }
 
 void LoadRegSettings()
-{   
+{
     HKEY hRegData;
 
     /** Many users have had problems using older versions and wanting to send
      * files from a third party application. Having this value in the registry
      * will allow users to send files without specifying the dia version to run.
      */
-    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\GNU\\dia-win-remote", 
+    if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\\GNU\\dia-win-remote",
                      0, KEY_READ, &hRegData) == ERROR_SUCCESS)
     {
         DWORD dwSize = sizeof(gszDiaExe);
diff --git a/app/diagram.c b/app/diagram.c
index a8d75af1..aa2f0f1f 100644
--- a/app/diagram.c
+++ b/app/diagram.c
@@ -150,11 +150,8 @@ dia_diagram_finalize (GObject *object)
   assert (dia->displays==NULL);
 
   g_clear_object (&priv->file);
-
-  if (dia->filename)
-    g_free (dia->filename);
-  dia->filename = NULL;
-
+  g_clear_pointer (&dia->filename, g_free);
+  
   G_OBJECT_CLASS (dia_diagram_parent_class)->finalize (object);
 }
 
@@ -314,17 +311,17 @@ diagram_load_into (Diagram         *diagram,
 
         if (suffix_offset != NULL) {
           new_filename = g_strndup (old_filename, suffix_offset - old_filename);
-          g_free (old_filename);
+          g_clear_pointer (&old_filename, g_free);
         } else {
           new_filename = old_filename;
         }
         old_filename = g_strconcat (new_filename, ".dia", NULL);
-        g_free (new_filename);
+        g_clear_pointer (&new_filename, g_free);
 
         file = g_file_new_for_path (old_filename);
         dia_diagram_set_file (diagram, file);
 
-        g_free (old_filename);
+        g_clear_pointer (&old_filename, g_free);
 
         diagram->unsaved = TRUE;
 
@@ -418,11 +415,12 @@ dia_diagram_new (GFile *file)
   return dia;
 }
 
+// TODO: This seems bad
 void
 diagram_destroy(Diagram *dia)
 {
   g_signal_emit (dia, diagram_signals[REMOVED], 0);
-  g_object_unref(dia);
+  g_clear_object (&dia);
 }
 
 /** Returns true if we consider the diagram modified.
@@ -444,8 +442,8 @@ diagram_modified(Diagram *dia)
   gchar *extra = g_path_get_dirname (dia->filename);
   gchar *title = g_strdup_printf ("%s%s (%s)", diagram_is_modified(dia) ? "*" : "", dia_name, extra ? extra 
: " ");
 
-  g_free (dia_name);
-  g_free (extra);
+  g_clear_pointer (&dia_name, g_free);
+  g_clear_pointer (&extra, g_free);
   displays = dia->displays;
   while (displays!=NULL) {
     DDisplay *ddisp = (DDisplay *) displays->data;
@@ -459,7 +457,7 @@ diagram_modified(Diagram *dia)
     dia->is_default = FALSE;
   }
   /*  diagram_set_modified(dia, TRUE);*/
-  g_free (title);
+  g_clear_pointer (&title, g_free);
 }
 
 /** Set this diagram explicitly modified.  This should not be called
@@ -1593,7 +1591,7 @@ dia_diagram_set_file (Diagram *self,
     l = g_slist_next (l);
   }
 
-  g_free (title);
+  g_clear_pointer (&title, g_free);
 
   /* signal about the change */
   dia_application_diagram_change (dia_application_get_default (),
diff --git a/app/diagram_tree_model.c b/app/diagram_tree_model.c
index 25aa63d4..cb5a52b4 100644
--- a/app/diagram_tree_model.c
+++ b/app/diagram_tree_model.c
@@ -575,27 +575,38 @@ _dtm_finalize (GObject *object)
   G_OBJECT_CLASS(_dtm_parent_class)->finalize (object);
 }
 
+
 /* SORTABLE
  * Wrapper around the original model to allow sorting by various columns IDs
  */
-static gint
-cmp_diagram (GtkTreeIter  *a,
-            GtkTreeIter  *b)
+static int
+cmp_diagram (GtkTreeIter *a,
+             GtkTreeIter *b)
 {
-  DiagramData *pa = NODE_DIAGRAM(a), *pb = NODE_DIAGRAM(b);
-  gchar *na, *nb;
-  gint ret;
-  if (pa == pb)
+  DiagramData *pa = NODE_DIAGRAM (a), *pb = NODE_DIAGRAM (b);
+  char *na, *nb;
+  int ret;
+
+  if (pa == pb) {
     return 0;
-  na = diagram_get_name (DIA_DIAGRAM(pa));
-  nb = diagram_get_name (DIA_DIAGRAM(pa));
-  if (!na || !nb)
+  }
+
+  na = diagram_get_name (DIA_DIAGRAM (pa));
+  nb = diagram_get_name (DIA_DIAGRAM (pa));
+
+  if (!na || !nb) {
     return (na > nb) ? -1 : 1;
+  }
+
   ret = strcmp (na, nb);
-  g_free (na);
-  g_free (nb);
+
+  g_clear_pointer (&na, g_free);
+  g_clear_pointer (&nb, g_free);
+
   return ret;
 }
+
+
 static gint
 cmp_layer (GtkTreeIter  *a,
           GtkTreeIter  *b)
@@ -613,33 +624,50 @@ cmp_layer (GtkTreeIter  *a,
 
   return ret;
 }
-static gint
+
+
+static int
 name_sort_func (GtkTreeModel *model,
-               GtkTreeIter  *a,
-               GtkTreeIter  *b,
-               gpointer      user_data)
+                GtkTreeIter  *a,
+                GtkTreeIter  *b,
+                gpointer      user_data)
 {
-  DiaObject *pa = NODE_OBJECT(a), *pb = NODE_OBJECT(b);
-  gchar *na, *nb;
-  gint ret = cmp_diagram (a, b);
-  if (ret)
+  DiaObject *pa = NODE_OBJECT (a), *pb = NODE_OBJECT (b);
+  char *na, *nb;
+  int ret = cmp_diagram (a, b);
+
+  if (ret) {
     return ret;
+  }
+
   ret = cmp_layer (a, b);
-  if (ret)
+
+  if (ret) {
     return ret;
-  if (pa == pb)
+  }
+
+  if (pa == pb) {
     return 0;
-  else if (!pa || !pb)
+  } else if (!pa || !pb) {
     return (pa > pb) ? -1 : 1;
+  }
+
   na = object_get_displayname (pa);
   nb = object_get_displayname (pb);
-  if (!na || !nb)
-      return (na > nb) ? -1 : 1;
+
+  if (!na || !nb) {
+    return (na > nb) ? -1 : 1;
+  }
+
   ret = strcmp (na, nb);
-  g_free (na);
-  g_free (nb);
+
+  g_clear_pointer (&na, g_free);
+  g_clear_pointer (&nb, g_free);
+
   return ret;
 }
+
+
 static gint
 type_sort_func (GtkTreeModel *model,
                GtkTreeIter  *a,
diff --git a/app/diagram_tree_view.c b/app/diagram_tree_view.c
index 79fc0ac9..f96cda51 100644
--- a/app/diagram_tree_view.c
+++ b/app/diagram_tree_view.c
@@ -100,25 +100,25 @@ _dtv_button_press (GtkWidget      *widget,
       gtk_tree_path_free (path);
     }
 
-    gtk_menu_popup (DIAGRAM_TREE_VIEW(widget)->popup, NULL, NULL, NULL, NULL, event->button, event->time);
-
+    gtk_menu_popup (DIAGRAM_TREE_VIEW (widget)->popup, NULL, NULL, NULL, NULL, event->button, event->time);
   } else {
     GTK_WIDGET_CLASS (_dtv_parent_class)->button_press_event (widget, event);
 
     if (gtk_tree_view_get_path_at_pos (GTK_TREE_VIEW (widget),
-                                       event->x, event->y,
-                                        &path, NULL, NULL, NULL)) {
+                                       event->x, event->y,
+                                       &path, NULL, NULL, NULL)) {
       model = gtk_tree_view_get_model (GTK_TREE_VIEW (widget));
       gtk_tree_model_get_iter (model, &iter, path);
       gtk_tree_model_get (model, &iter, OBJECT_COLUMN, &object, -1);
       gtk_tree_model_get (model, &iter, DIAGRAM_COLUMN, &diagram, -1);
 
-      if (object && diagram && ddisplay_active_diagram() == diagram) {
-       if (event->button == 1 && event->type == GDK_2BUTTON_PRESS) /* double-click 'locates' */
-         ddisplay_present_object (ddisplay_active(), object);
+      if (object && diagram && ddisplay_active_diagram () == diagram) {
+        if (event->button == 1 && event->type == GDK_2BUTTON_PRESS) {
+          /* double-click 'locates' */
+          ddisplay_present_object (ddisplay_active(), object);
+        }
       }
-      if (diagram)
-       g_object_unref(diagram);
+      g_clear_object (&diagram);
       gtk_tree_path_free (path);
     }
   }
@@ -126,6 +126,7 @@ _dtv_button_press (GtkWidget      *widget,
   return TRUE;
 }
 
+
 static gboolean
 _dtv_query_tooltip (GtkWidget  *widget,
                     gint        x,
@@ -163,34 +164,61 @@ _dtv_query_tooltip (GtkWidget  *widget,
       markup = g_string_new (NULL);
 
       if (diagram) {
-        gchar *em = g_markup_printf_escaped ("<b>%s</b>: %s\n", _("Diagram"), diagram->filename);
+        char *em = g_markup_printf_escaped ("<b>%s</b>: %s\n",
+                                            _("Diagram"),
+                                            diagram->filename);
+
         g_string_append (markup, em);
-        g_free (em);
+
+        g_clear_pointer (&em, g_free);
       }
 
       if (layer) {
         const char *name = dia_layer_get_name (layer);
-        gchar *em = g_markup_printf_escaped ("<b>%s</b>: %s\n", _("Layer"), name);
+        char *em = g_markup_printf_escaped ("<b>%s</b>: %s\n",
+                                            _("Layer"),
+                                            name);
+
         g_string_append (markup, em);
-        g_free (em);
+
+        g_clear_pointer (&em, g_free);
       } else if (diagram) {
-       int layers = data_layer_count (DIA_DIAGRAM_DATA (diagram));
-       g_string_append_printf (markup, g_dngettext (GETTEXT_PACKAGE, "%d Layer", "%d Layers",
-                               layers), layers);
+        int layers = data_layer_count (DIA_DIAGRAM_DATA (diagram));
+
+        g_string_append_printf (markup,
+                                g_dngettext (GETTEXT_PACKAGE,
+                                             "%d Layer",
+                                             "%d Layers",
+                                             layers),
+                                layers);
       }
+
       if (object) {
-        gchar *em = g_markup_printf_escaped ("<b>%s</b>: %s\n", _("Type"), object->type->name);
+        char *em = g_markup_printf_escaped ("<b>%s</b>: %s\n",
+                                            _("Type"),
+                                            object->type->name);
+
         g_string_append (markup, em);
-        g_free (em);
-        g_string_append_printf (markup, "<b>%s</b>: %g,%g\n", Q_("object|Position"),
-                               object->position.x, object->position.y);
-       g_string_append_printf (markup, "%d %s",
-                               g_list_length (object->children), _("Children"));
+
+        g_clear_pointer (&em, g_free);
+
+        g_string_append_printf (markup,
+                                "<b>%s</b>: %g,%g\n",
+                                Q_("object|Position"),
+                                object->position.x,
+                                object->position.y);
+        g_string_append_printf (markup,
+                                "%d %s",
+                                g_list_length (object->children),
+                                _("Children"));
         /* and some dia_object_get_meta ? */
       } else if (layer) {
         int objects = dia_layer_object_count (layer);
+
         g_string_append_printf (markup,
-                                g_dngettext (GETTEXT_PACKAGE, "%d Object", "%d Objects",
+                                g_dngettext (GETTEXT_PACKAGE,
+                                             "%d Object",
+                                             "%d Objects",
                                              objects),
                                 objects);
       }
@@ -198,29 +226,35 @@ _dtv_query_tooltip (GtkWidget  *widget,
       if (markup->len > 0) {
         gtk_tree_view_get_cell_area (GTK_TREE_VIEW (widget), path, column, &cell_area);
 
-        gtk_tree_view_convert_bin_window_to_widget_coords
-                       (GTK_TREE_VIEW (widget), cell_area.x, cell_area.y,
-                        &cell_area.x, &cell_area.y);
+        gtk_tree_view_convert_bin_window_to_widget_coords (GTK_TREE_VIEW (widget),
+                                                           cell_area.x,
+                                                           cell_area.y,
+                                                           &cell_area.x,
+                                                           &cell_area.y);
 
         gtk_tooltip_set_tip_area (tooltip, &cell_area);
         gtk_tooltip_set_markup (tooltip, markup->str);
-       had_info = TRUE;
+        had_info = TRUE;
       }
 
       /* drop references */
-      if (diagram)
-        g_object_unref (diagram);
+      g_clear_object (&diagram);
       g_string_free (markup, TRUE);
     }
     gtk_tree_path_free (path);
-    if (had_info)
+    if (had_info) {
       return TRUE;
+    }
   }
 
-  return GTK_WIDGET_CLASS (_dtv_parent_class)->query_tooltip
-                                               (widget, x, y, keyboard_mode, tooltip);
+  return GTK_WIDGET_CLASS (_dtv_parent_class)->query_tooltip (widget,
+                                                              x,
+                                                              y,
+                                                              keyboard_mode,
+                                                              tooltip);
 }
 
+
 static void
 _dtv_row_activated (GtkTreeView       *view,
                    GtkTreePath       *path,
@@ -292,10 +326,10 @@ _dtv_cell_pixbuf_func (GtkCellLayout   *layout,
   }
 
   g_object_set (cell, "pixbuf", pixbuf, NULL);
-  if (pixbuf)
-    g_object_unref (pixbuf);
+  g_clear_object (&pixbuf);
 }
 
+
 static void
 _dtv_select_items (GtkAction *action,
                   DiagramTreeView *dtv)
@@ -331,8 +365,8 @@ _dtv_select_items (GtkAction *action,
         diagram_select (diagram, object);
       if (diagram) {
         diagram_add_update_all (diagram);
-        diagram_flush(diagram);
-        g_object_unref (diagram);
+        diagram_flush (diagram);
+        g_clear_object (&diagram);
       }
     }
     r = g_list_next (r);
@@ -377,9 +411,7 @@ _dtv_locate_item (GtkAction *action,
         }
       }
       /* drop all references got from the model */
-      if (diagram) {
-        g_object_unref (diagram);
-      }
+      g_clear_object (&diagram);
     }
     r = g_list_next (r);
   }
@@ -408,26 +440,32 @@ _dtv_showprops_item (GtkAction *action,
 
       gtk_tree_model_get (model, &iter, DIAGRAM_COLUMN, &current_diagram, -1);
       gtk_tree_model_get (model, &iter, OBJECT_COLUMN, &object, -1);
-      if (object)
+
+      if (object) {
         selected = g_list_append (selected, object);
-      if (!diagram) /* keep the reference */
+      }
+
+      if (!diagram) {
+        /* keep the reference */
         diagram = current_diagram;
-      else if (diagram == current_diagram) /* still the same */
-        g_object_unref (current_diagram);
-      else {
-        g_object_unref (current_diagram);
-       break; /* can only handle one diagram's objects */
+      } else if (diagram == current_diagram) {
+        /* still the same */
+        g_clear_object (&current_diagram);
+      } else {
+        g_clear_object (&current_diagram);
+        break; /* can only handle one diagram's objects */
       }
     }
     r = g_list_next (r);
   }
 
-  if (diagram && selected)
+  if (diagram && selected) {
     object_list_properties_show (diagram, selected);
-  else if (diagram)
-    diagram_properties_show(diagram);
-  if (diagram)
-    g_object_unref(diagram);
+  } else if (diagram) {
+    diagram_properties_show (diagram);
+  }
+
+  g_clear_object (&diagram);
 
   g_list_foreach (rows, (GFunc) gtk_tree_path_free, NULL);
   g_list_free (rows);
diff --git a/app/disp_callbacks.c b/app/disp_callbacks.c
index f1dbb7d4..000aa9ce 100644
--- a/app/disp_callbacks.c
+++ b/app/disp_callbacks.c
@@ -96,15 +96,15 @@ object_menu_item_proxy(GtkWidget *widget, gpointer data)
   diagram_flush(ddisp->diagram);
 }
 
+
 static void
 dia_menu_free(DiaMenu *dia_menu)
 {
-  if (dia_menu->app_data)
-    g_object_unref ((GObject *)dia_menu->app_data);
-  dia_menu->app_data = NULL;
+  g_clear_object (&dia_menu->app_data);
   dia_menu->app_data_free = NULL;
 }
 
+
 /*
   This add a Properties... menu item to the GtkMenu passed, at the
   end and set the callback to raise de properties dialog
@@ -128,16 +128,18 @@ add_properties_menu_item (GtkMenu *menu, gboolean separator)
   gtk_menu_shell_append (GTK_MENU_SHELL (menu), menu_item);
   gtk_widget_show(menu_item);
 }
+
+
 static void
 _follow_link_callback (GtkAction *action, gpointer data)
 {
   DiaObject *obj;
   DDisplay *ddisp = ddisplay_active();
-  gchar *url;
+  char *url;
 
   if (!ddisp) return;
 
-  obj = (DiaObject *)ddisp->diagram->data->selected->data;
+  obj = (DiaObject *) ddisp->diagram->data->selected->data;
 
   url = dia_object_get_meta (obj, "url");
 
@@ -147,18 +149,24 @@ _follow_link_callback (GtkAction *action, gpointer data)
     if (!g_path_is_absolute(url)) {
       gchar *p = NULL;
 
-      if (ddisp->diagram->filename)
+      if (ddisp->diagram->filename) {
         p = dia_absolutize_filename (ddisp->diagram->filename, url);
+      }
+
       if (p) {
-       g_free (url);
-       url = p;
+        g_clear_pointer (&url, g_free);
+        url = p;
       }
     }
     dia_file_open (url, NULL);
-  } else
+  } else {
     activate_url (GTK_WIDGET (ddisp->shell), url, NULL);
-  g_free (url);
+  }
+
+  g_clear_pointer (&url, g_free);
 }
+
+
 static void
 add_follow_link_menu_item (GtkMenu *menu)
 {
@@ -1227,11 +1235,11 @@ ddisplay_drop_object(DDisplay *ddisp, gint x, gint y, DiaObjectType *otype,
     }
 
     if (child_width > parent_width ||
-       child_height > parent_height) {
-      message_error(_("The object you dropped cannot fit into its parent. \nEither expand the parent object, 
or drop the object elsewhere."));
+        child_height > parent_height) {
+      message_error (_("The object you dropped cannot fit into its parent. \nEither expand the parent 
object, or drop the object elsewhere."));
       obj->parent->children = g_list_remove(obj->parent->children, obj);
       obj->ops->destroy (obj);
-      g_free (obj);
+      g_clear_pointer (&obj, g_free);
       return NULL;
     }
 
diff --git a/app/display.c b/app/display.c
index e3242a39..c94c1fc9 100644
--- a/app/display.c
+++ b/app/display.c
@@ -73,55 +73,57 @@ update_zoom_status (DDisplay *ddisp)
                         zoom_text);
   }
 
-  g_free (zoom_text); /* Copied by gtk_entry_set_text */
+  g_clear_pointer (&zoom_text, g_free); /* Copied by gtk_entry_set_text */
 }
 
+
 static void
-selection_changed (Diagram* dia, int n, DDisplay* ddisp)
+selection_changed (Diagram *dia, int n, DDisplay *ddisp)
 {
   GtkStatusbar *statusbar;
   guint context_id;
 
   /* nothing to do if there is no display with the diagram anymore */
-  if (g_slist_length(dia->displays) < 1)
+  if (g_slist_length (dia->displays) < 1) {
     return;
+  }
 
   statusbar = GTK_STATUSBAR (ddisp->modified_status);
   context_id = gtk_statusbar_get_context_id (statusbar, "Selection");
 
-  if (n > 1)
-  {
-    gchar *msg;
-
+  if (n > 1) {
     /* http://www.gnu.org/software/gettext/manual/html_chapter/gettext_10.html#SEC150
      * Althoug the single objects wont get triggered here some languages have variations on the other numbers
      */
-    msg = g_strdup_printf (ngettext ("Selection of %d object", "Selection of %d objects", n), n);
+    char *msg = g_strdup_printf (ngettext ("Selection of %d object",
+                                           "Selection of %d objects",
+                                           n),
+                                 n);
+
     gtk_statusbar_pop (statusbar, context_id);
     gtk_statusbar_push (statusbar, context_id, msg);
-    g_free (msg);
-  }
-  else if (n == 1)
-  {
+
+    g_clear_pointer (&msg, g_free);
+  } else if (n == 1) {
     /* find the selected objects name - and display it */
-    DiaObject *object = (DiaObject *)ddisp->diagram->data->selected->data;
-    gchar *name = object_get_displayname (object);
-    gchar *msg = g_strdup_printf (_("Selected '%s'"), _(name));
+    DiaObject *object = (DiaObject *) ddisp->diagram->data->selected->data;
+    char *name = object_get_displayname (object);
+    char *msg = g_strdup_printf (_("Selected '%s'"), _(name));
 
     gtk_statusbar_pop (statusbar, context_id);
     gtk_statusbar_push (statusbar, context_id, msg);
 
-    g_free (name);
-    g_free (msg);
-  }
-  else
-  {
+    g_clear_pointer (&name, g_free);
+    g_clear_pointer (&msg, g_free);
+  } else {
     gtk_statusbar_pop (statusbar, context_id);
   }
+
   /* selection-changed signal can also be emitted from outside of the dia core */
   ddisplay_do_update_menu_sensitivity (ddisp);
 }
 
+
 /** Initialize the various GTK-level thinks in a display after the internal
  *  data has been set.
  * @param ddisp A display with all non-GTK/GDK items set.
@@ -377,16 +379,11 @@ ddisplay_add_update_pixels (DDisplay *ddisp,
 static void
 ddisplay_free_update_areas (DDisplay *ddisp)
 {
-  GSList *l;
-  l = ddisp->update_areas;
-  while(l!=NULL) {
-    g_free(l->data);
-    l = g_slist_next(l);
-  }
-  g_slist_free(ddisp->update_areas);
+  g_slist_free_full (ddisp->update_areas, g_free);
   ddisp->update_areas = NULL;
 }
 
+
 /** Marks the entire visible area for update.
  * Throws out old updates, since everything will be updated anyway.
  */
@@ -1151,8 +1148,7 @@ ddisp_destroy (DDisplay *ddisp)
 {
   g_signal_handlers_disconnect_by_func (ddisp->diagram, selection_changed, ddisp);
 
-  g_object_unref (G_OBJECT (ddisp->im_context));
-  ddisp->im_context = NULL;
+  g_clear_object (&ddisp->im_context);
 
   ddisplay_im_context_preedit_reset (ddisp, get_active_focus ((DiagramData *) ddisp->diagram));
 
@@ -1324,10 +1320,9 @@ ddisplay_do_update_menu_sensitivity (DDisplay *ddisp)
 }
 
 
-
 /* This is called when ddisp->shell is destroyed... */
 void
-ddisplay_really_destroy(DDisplay *ddisp)
+ddisplay_really_destroy (DDisplay *ddisp)
 {
   if (active_display == ddisp)
     display_set_active(NULL);
@@ -1343,7 +1338,7 @@ ddisplay_really_destroy(DDisplay *ddisp)
   /* Free update_areas list: */
   ddisplay_free_update_areas(ddisp);
 
-  g_free(ddisp);
+  g_clear_pointer (&ddisp, g_free);
 }
 
 
@@ -1369,7 +1364,7 @@ ddisplay_set_title(DDisplay  *ddisp, char *title)
         /* not using the passed in title here, because it may be too long */
         gchar *name = diagram_get_name(ddisp->diagram);
         gtk_label_set_text(label,name);
-        g_free(name);
+        g_clear_pointer (&name, g_free);
         break;
       }
     }
@@ -1378,13 +1373,14 @@ ddisplay_set_title(DDisplay  *ddisp, char *title)
       const gchar *pname = g_get_prgname();
       gchar *fulltitle = g_strdup_printf ("%s - %s", title, pname ? pname : "Dia");
       gtk_window_set_title (GTK_WINDOW (ddisp->shell), fulltitle);
-      g_free(fulltitle);
+      g_clear_pointer (&fulltitle, g_free);
     }
   }
 }
 
+
 void
-ddisplay_set_all_cursor(GdkCursor *cursor)
+ddisplay_set_all_cursor (GdkCursor *cursor)
 {
   Diagram *dia;
   DDisplay *ddisp;
@@ -1578,13 +1574,10 @@ ddisplay_im_context_preedit_reset(DDisplay *ddisp, Focus *focus)
       }
     }
 
-    g_free(ddisp->preedit_string);
-    ddisp->preedit_string = NULL;
-  }
-  if (ddisp->preedit_attrs != NULL) {
-    pango_attr_list_unref(ddisp->preedit_attrs);
-    ddisp->preedit_attrs = NULL;
+    g_clear_pointer (&ddisp->preedit_string, g_free);
   }
+
+  g_clear_pointer (&ddisp->preedit_attrs, pango_attr_list_unref);
 }
 
 /** Get the active focus for the given display, or NULL.
diff --git a/app/exit_dialog.c b/app/exit_dialog.c
index 859a7cd8..16222d8d 100644
--- a/app/exit_dialog.c
+++ b/app/exit_dialog.c
@@ -1,4 +1,4 @@
-/* 
+/*
  * exit_dialog.h: Dialog to allow the user to choose which data to
  * save on exit or to cancel exit.
  *
@@ -98,7 +98,7 @@ exit_dialog_make (GtkWindow * parent_window,
     GdkGeometry geometry = { 0 };
 
     gtk_box_pack_start (vbox, label, FALSE, FALSE, 0);
-    
+
     gtk_widget_show (label);
 
     /* Scrolled window for displaying things which need saving */
@@ -118,7 +118,7 @@ exit_dialog_make (GtkWindow * parent_window,
     gtk_tree_view_append_column (GTK_TREE_VIEW (treeview), column);
 
     g_signal_connect (G_OBJECT (renderer), "toggled",
-                      G_CALLBACK (toggle_check_button), 
+                      G_CALLBACK (toggle_check_button),
                       treeview);
 
     renderer = gtk_cell_renderer_text_new ();
@@ -136,7 +136,7 @@ exit_dialog_make (GtkWindow * parent_window,
 
     gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW (scrolled), GTK_WIDGET (treeview));
 
- 
+
     hbox = gtk_hbox_new (FALSE, 3);
     gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, FALSE, 0);
     gtk_widget_show (hbox);
@@ -146,7 +146,7 @@ exit_dialog_make (GtkWindow * parent_window,
     gtk_widget_show (button);
 
     g_signal_connect (G_OBJECT (button), "clicked",
-                      G_CALLBACK (select_all_clicked), 
+                      G_CALLBACK (select_all_clicked),
                       treeview);
 
     button = gtk_button_new_with_label (_("Select None"));
@@ -154,18 +154,18 @@ exit_dialog_make (GtkWindow * parent_window,
     gtk_widget_show (button);
 
     g_signal_connect (G_OBJECT (button), "clicked",
-                      G_CALLBACK (select_none_clicked), 
+                      G_CALLBACK (select_none_clicked),
                       treeview);
 
-    g_object_unref (model);
+    g_clear_object (&model);
     gtk_widget_show (GTK_WIDGET (treeview));
 
     gtk_widget_show_all (GTK_WIDGET(vbox));
 
     g_object_set_data (G_OBJECT (dialog), EXIT_DIALOG_TREEVIEW,  treeview);
-    
+
     g_signal_connect (G_OBJECT (dialog), "destroy",
-                      G_CALLBACK (exit_dialog_destroy), 
+                      G_CALLBACK (exit_dialog_destroy),
                       treeview);
 
     /* golden ratio */
@@ -186,8 +186,8 @@ exit_dialog_make (GtkWindow * parent_window,
  */
 void
 exit_dialog_add_item (GtkWidget *    dialog,
-                      const gchar *  name, 
-                      const gchar *  path, 
+                      const gchar *  name,
+                      const gchar *  path,
                       const gpointer optional_data)
 {
     GtkTreeView *  treeview;
@@ -197,8 +197,8 @@ exit_dialog_add_item (GtkWidget *    dialog,
     const gchar *  path_copy = g_strdup (path);
 
     treeview = g_object_get_data (G_OBJECT (dialog), EXIT_DIALOG_TREEVIEW);
-  
-    model = GTK_LIST_STORE (gtk_tree_view_get_model (treeview)); 
+
+    model = GTK_LIST_STORE (gtk_tree_view_get_model (treeview));
 
     gtk_list_store_append (model, &iter);
 
@@ -216,12 +216,12 @@ exit_dialog_run (GtkWidget * dialog,
 {
     gint                       result;
     gint                       count;
-    
+
     while (TRUE)
     {
         result = gtk_dialog_run ( GTK_DIALOG(dialog));
 
-        switch (result) 
+        switch (result)
         {
             case EXIT_DIALOG_EXIT_CANCEL:
             case EXIT_DIALOG_EXIT_NO_SAVE:
@@ -232,9 +232,9 @@ exit_dialog_run (GtkWidget * dialog,
            default : /* e.g. if closed by window manager button */
                return EXIT_DIALOG_EXIT_CANCEL;
         }
-    
+
         count = get_selected_items (dialog, items);
-    
+
         if (count == 0)
         {
            GtkWidget * msg_dialog = gtk_message_dialog_new (GTK_WINDOW (dialog),
@@ -266,53 +266,51 @@ exit_dialog_run (GtkWidget * dialog,
  * @param items Structure to hold the selected items.  Set to NULL if not items selected.
  * @return The number of selected items.
  */
-gint
-get_selected_items (GtkWidget * dialog,
-                    exit_dialog_item_array_t ** items)
+int
+get_selected_items (GtkWidget                 *dialog,
+                    exit_dialog_item_array_t **items)
 {
-    GtkTreeView *              treeview;
-    GtkTreeIter                iter;
-    GtkListStore *             model;
-    gboolean                   valid;
-    GSList *                   list = NULL;
-    GSList *                   list_iter;
-    gint                       selected_count;
-    gint                       i;
-
-    treeview = g_object_get_data (G_OBJECT (dialog), EXIT_DIALOG_TREEVIEW);
-  
-    model = GTK_LIST_STORE (gtk_tree_view_get_model (treeview)); 
-  
-    /* Get the first iter in the list */
-    valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (model), &iter);
-
-    /* Get the selected items */
-    while (valid)
-    {
-        const char * name;
-        const char * path;
-        gpointer     data;
-        gboolean     is_selected;
-
-        gtk_tree_model_get (GTK_TREE_MODEL (model), &iter, 
-                            CHECK_COL, &is_selected,
-                            NAME_COL,  &name,
-                            PATH_COL,  &path,
-                            DATA_COL,  &data,
-                            -1);
+  GtkTreeView  *treeview;
+  GtkTreeIter   iter;
+  GtkListStore *model;
+  gboolean      valid;
+  GSList       *list = NULL;
+  GSList       *list_iter;
+  int           selected_count;
+  int           i;
+
+  treeview = g_object_get_data (G_OBJECT (dialog), EXIT_DIALOG_TREEVIEW);
+
+  model = GTK_LIST_STORE (gtk_tree_view_get_model (treeview));
+
+  /* Get the first iter in the list */
+  valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (model), &iter);
+
+  /* Get the selected items */
+  while (valid) {
+    char     *name;
+    char     *path;
+    gpointer  data;
+    gboolean  is_selected;
+
+    gtk_tree_model_get (GTK_TREE_MODEL (model), &iter,
+                        CHECK_COL, &is_selected,
+                        NAME_COL,  &name,
+                        PATH_COL,  &path,
+                        DATA_COL,  &data,
+                        -1);
 
-        if (is_selected)
-        {
-            exit_dialog_item_t * item = g_new (exit_dialog_item_t,1);
-            item->name = name;
-            item->path = path;
-            item->data = data;
-            list = g_slist_prepend (list, item);
-        }
-        
-        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (model), &iter);
+    if (is_selected) {
+      exit_dialog_item_t *item = g_new (exit_dialog_item_t, 1);
+      item->name = name;
+      item->path = path;
+      item->data = data;
+      list = g_slist_prepend (list, item);
     }
 
+    valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (model), &iter);
+  }
+
     selected_count = g_slist_length (list);
 
     if (selected_count > 0)
@@ -320,7 +318,7 @@ get_selected_items (GtkWidget * dialog,
         *items              = g_new (exit_dialog_item_array_t,1);
        (*items)->array_size = selected_count;
        (*items)->array      = g_new (exit_dialog_item_t, (*items)->array_size);
-    
+
         list_iter = list;
         for(i = 0 ; i < selected_count ; i++)
         {
@@ -332,7 +330,7 @@ get_selected_items (GtkWidget * dialog,
             (*items)->array[i].data = item->data;
             list_iter = g_slist_next(list_iter);
         }
-    
+
         g_slist_free (list);
     }
     else
@@ -343,28 +341,28 @@ get_selected_items (GtkWidget * dialog,
     return selected_count;
 }
 
+
 /**
  * Free memory allocated for the exit_dialog_item_array_t.  This
  * will not free any memory not allocated by the dialog itself
  * @param items Item array struct returned by exit_dialog_run()
  */
-void exit_dialog_free_items (exit_dialog_item_array_t * items)
+void
+exit_dialog_free_items (exit_dialog_item_array_t * items)
 {
-  if (items)
-  {
-    int i;
-    for (i = 0 ; i < items->array_size ; i++)
-    {
+  if (items) {
+    for (int i = 0 ; i < items->array_size ; i++) {
       /* Cast is needed to remove warning because of const decl */
-      g_free ( (char*)items->array[i].name);
-      g_free ( (char*)items->array[i].path);
+      g_clear_pointer (&items->array[i].name, g_free);
+      g_clear_pointer (&items->array[i].path, g_free);
     }
 
-    g_free (items);
+    g_clear_pointer (&items, g_free);
   }
 }
 
-/** 
+
+/**
  * Handler for the check box (button) in the exit dialogs treeview.
  * This is needed to cause the check box to change state when the
  * user clicks it
@@ -372,7 +370,7 @@ void exit_dialog_free_items (exit_dialog_item_array_t * items)
 static void toggle_check_button (GtkCellRendererToggle * renderer,
                                  gchar * path,
                                  GtkTreeView * treeview)
-{ 
+{
     GtkTreeModel * model;
     GtkTreeIter    iter;
     gboolean       value;
@@ -385,44 +383,46 @@ static void toggle_check_button (GtkCellRendererToggle * renderer,
     }
 }
 
+
 /*
  * Signal handler for "destroy" event to free memory allocated for the exit_dialog.
  *
- * @param exit_dialog 
+ * @param exit_dialog
  * @param data Exit dialog's treeview
  */
-static void exit_dialog_destroy  (GtkWidget * exit_dialog,
-                                  gpointer    data)
+static void
+exit_dialog_destroy (GtkWidget *exit_dialog,
+                     gpointer   data)
 {
-    GtkTreeView *  treeview;
-    GtkTreeIter    iter;
-    GtkTreeModel * model;
-    gboolean       valid;
-  
-    treeview = g_object_get_data (G_OBJECT (exit_dialog), EXIT_DIALOG_TREEVIEW);
+  GtkTreeView  *treeview;
+  GtkTreeIter   iter;
+  GtkTreeModel *model;
+  gboolean      valid;
 
-    model = GTK_TREE_MODEL (gtk_tree_view_get_model (treeview)); 
-    
-    /* Get the first iter in the list */
-    valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (model), &iter);
+  treeview = g_object_get_data (G_OBJECT (exit_dialog), EXIT_DIALOG_TREEVIEW);
 
-    while (valid)
-    {
-        gchar * name = NULL;
-        gchar * path = NULL;
+  model = GTK_TREE_MODEL (gtk_tree_view_get_model (treeview));
 
-        gtk_tree_model_get (model, &iter,
-                            NAME_COL, &name,
-                            PATH_COL, &path,
-                            -1);
+  /* Get the first iter in the list */
+  valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (model), &iter);
 
-        g_free (name);
-        g_free (path);
+  while (valid) {
+    char *name = NULL;
+    char *path = NULL;
 
-        valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (model), &iter);
-    }
+    gtk_tree_model_get (model, &iter,
+                        NAME_COL, &name,
+                        PATH_COL, &path,
+                        -1);
+
+    g_clear_pointer (&name, g_free);
+    g_clear_pointer (&path, g_free);
+
+    valid = gtk_tree_model_iter_next (GTK_TREE_MODEL (model), &iter);
+  }
 }
 
+
 /**
  * Sets the state of the save checkbox in the treeview to the
  * state specified by the caller.
@@ -436,8 +436,8 @@ static void selected_state_set_all (GtkTreeView * treeview,
     GtkListStore * model;
     gboolean       valid;
 
-    model = GTK_LIST_STORE (gtk_tree_view_get_model (treeview)); 
-  
+    model = GTK_LIST_STORE (gtk_tree_view_get_model (treeview));
+
     /* Get the first iter in the list */
     valid = gtk_tree_model_get_iter_first (GTK_TREE_MODEL (model), &iter);
 
diff --git a/app/exit_dialog.h b/app/exit_dialog.h
index 30d7df92..88e489e6 100644
--- a/app/exit_dialog.h
+++ b/app/exit_dialog.h
@@ -1,4 +1,4 @@
-/* 
+/*
  * exit_dialog.h: Dialog to allow the user to choose which data to
  * save on exit or to cancel exit.
  *
@@ -37,19 +37,19 @@ exit_dialog_make (GtkWindow * parent_window,
                   gchar *     title);
 
 void
-exit_dialog_add_item (GtkWidget *    dialog,
-                      const gchar *  name, 
-                      const gchar *  filepath, 
-                      const gpointer optional_data);
+exit_dialog_add_item (GtkWidget      *dialog,
+                      const char     *name,
+                      const char     *filepath,
+                      const gpointer  optional_data);
 
-typedef struct 
-{
-  const gchar * name;
-  const gchar * path;
-  gpointer      data;
 
+typedef struct {
+  char     *name;
+  char     *path;
+  gpointer  data;
 } exit_dialog_item_t;
 
+
 typedef struct
 {
   size_t               array_size;
diff --git a/app/filedlg.c b/app/filedlg.c
index cefa6c8d..fa2ad4a8 100644
--- a/app/filedlg.c
+++ b/app/filedlg.c
@@ -199,7 +199,7 @@ create_open_menu(void)
       continue;
     filter_label = filter_get_import_filter_label(ifilter);
     gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(menu), filter_label);
-    g_free(filter_label);
+    g_clear_pointer (&filter_label, g_free);
   }
   g_signal_connect (G_OBJECT (menu), "changed",
                     G_CALLBACK (import_adapt_extension_callback), NULL);
@@ -226,7 +226,7 @@ file_open_response_callback(GtkWidget *fs,
 
     diagram = diagram_load(filename, ifilter_by_index (index - 1, filename));
 
-    g_free (filename);
+    g_clear_pointer (&filename, g_free);
 
     if (diagram != NULL) {
       diagram_update_extents(diagram);
@@ -239,7 +239,7 @@ file_open_response_callback(GtkWidget *fs,
        for (; displays != NULL; displays = g_slist_next(displays)) {
          DDisplay *loaded_display = (DDisplay *)displays->data;
          copy_display(loaded_display);
-         g_free(loaded_display);
+         g_clear_pointer (&loaded_display, g_free);
        }
        g_slist_free(displays_head);
       } else {
@@ -294,8 +294,8 @@ file_open_callback(GtkAction *action)
       char* fnabs = dia_get_absolute_filename (filename);
       if (fnabs)
         gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(opendlg), fnabs);
-      g_free(fnabs);
-      g_free(filename);
+      g_clear_pointer (&fnabs, g_free);
+      g_clear_pointer (&filename, g_free);
     }
     g_signal_connect (G_OBJECT (opendlg), "destroy",
                       G_CALLBACK (gtk_widget_destroyed), &opendlg);
@@ -389,15 +389,15 @@ file_save_as_response_callback(GtkWidget *fs,
       gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog),
         _("The file '%s' already exists.\n"
           "Do you want to overwrite it?"), utf8filename);
-      g_free(utf8filename);
+      g_clear_pointer (&utf8filename, g_free);
       gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_YES);
 
       if (gtk_dialog_run (GTK_DIALOG (dialog)) != GTK_RESPONSE_YES) {
-       /* don't hide/destroy the dialog, but simply go back to it */
-       gtk_window_present (GTK_WINDOW (fs));
-       gtk_widget_destroy(dialog);
-        g_free (filename);
-       return;
+        /* don't hide/destroy the dialog, but simply go back to it */
+        gtk_window_present (GTK_WINDOW (fs));
+        gtk_widget_destroy (dialog);
+        g_clear_pointer (&filename, g_free);
+        return;
       }
       gtk_widget_destroy(dialog);
     }
@@ -420,16 +420,16 @@ file_save_as_response_callback(GtkWidget *fs,
       dia_context_release (ctx);
       g_clear_object (&file);
     }
-    g_free (filename);
+    g_clear_pointer (&filename, g_free);
   }
+
   /* if we have our own reference, drop it before destroy */
-  if ((dia = g_object_get_data (G_OBJECT(fs), "user_data")) != NULL) {
-    g_object_set_data (G_OBJECT(fs), "user_data", NULL);
-    g_object_unref (dia);
-  }
+  g_object_set_data (G_OBJECT (fs), "user_data", NULL);
+
   /* if we destroy it gtk_dialog_run wont give the response */
-  if (!g_object_get_data (G_OBJECT(fs), "dont-destroy"))
-    gtk_widget_destroy(GTK_WIDGET(fs));
+  if (!g_object_get_data (G_OBJECT(fs), "dont-destroy")) {
+    gtk_widget_destroy (GTK_WIDGET (fs));
+  }
 }
 
 static GtkWidget *file_save_as_dialog_prepare (Diagram *dia, DDisplay *ddisp);
@@ -518,12 +518,12 @@ file_save_as_dialog_prepare (Diagram *dia, DDisplay *ddisp)
     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(compressbutton),
                                 dia->data->is_compressed);
     g_signal_handlers_unblock_by_func(G_OBJECT(compressbutton), toggle_compress_callback, NULL);
-    if (g_object_get_data (G_OBJECT (savedlg), "user_data") != NULL)
-      g_object_unref (g_object_get_data (G_OBJECT (savedlg), "user_data"));
     if (gtk_widget_get_visible (savedlg)) {
       /* keep a refernce to the diagram */
-      g_object_ref (dia);
-      g_object_set_data (G_OBJECT (savedlg), "user_data", dia);
+      g_object_set_data_full (G_OBJECT (savedlg),
+                              "user_data",
+                              g_object_ref (dia),
+                              g_object_unref);
       gtk_window_present (GTK_WINDOW (savedlg));
       return savedlg;
     }
@@ -538,13 +538,16 @@ file_save_as_dialog_prepare (Diagram *dia, DDisplay *ddisp)
       /* FileChooser api insist on exiting files for set_filename  */
       /* ... and does not use filename encoding on this one. */
       gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(savedlg), base);
-      g_free(base);
+      g_clear_pointer (&base, g_free);
     }
-    g_free(fnabs);
-    g_free(filename);
+    g_clear_pointer (&fnabs, g_free);
+    g_clear_pointer (&filename, g_free);
   }
-  g_object_ref(dia);
-  g_object_set_data (G_OBJECT (savedlg), "user_data", dia);
+
+  g_object_set_data_full (G_OBJECT (savedlg),
+                          "user_data",
+                          g_object_ref (dia),
+                          g_object_unref);
 
   return savedlg;
 }
@@ -570,7 +573,7 @@ file_save_callback(GtkAction *action)
     diagram_update_extents(diagram);
     if (diagram_save(diagram, filename, ctx))
       recent_file_history_add(filename);
-    g_free (filename);
+    g_clear_pointer (&filename, g_free);
     dia_context_release (ctx);
   }
 }
@@ -622,10 +625,12 @@ export_adapt_extension (const gchar* name, int index)
     utf8_name = g_filename_to_utf8 (s->str, -1, NULL, NULL, NULL);
     g_string_free (s, TRUE);
   }
-  gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(exportdlg), utf8_name);
-  g_free (utf8_name);
-  g_free (basename);
+  gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (exportdlg), utf8_name);
+  g_clear_pointer (&utf8_name, g_free);
+  g_clear_pointer (&basename, g_free);
 }
+
+
 static void
 export_adapt_extension_callback(GtkWidget *widget)
 {
@@ -634,7 +639,7 @@ export_adapt_extension_callback(GtkWidget *widget)
 
   if (name && index > 0) /* Ignore "By Extension" */
     export_adapt_extension (name, index - 1);
-  g_free (name);
+  g_clear_pointer (&name, g_free);
 }
 
 /**
@@ -655,9 +660,10 @@ create_export_menu (void)
 
     if (!ef)
       continue;
+
     filter_label = filter_get_export_filter_label (ef);
     gtk_combo_box_text_append_text (GTK_COMBO_BOX_TEXT(menu), filter_label);
-    g_free (filter_label);
+    g_clear_pointer (&filter_label, g_free);
   }
   g_signal_connect (G_OBJECT (menu), "changed",
                     G_CALLBACK (export_adapt_extension_callback), NULL);
@@ -701,38 +707,49 @@ file_export_response_callback(GtkWidget *fs,
       gtk_dialog_set_default_response (GTK_DIALOG (dialog), GTK_RESPONSE_YES);
 
       if (gtk_dialog_run (GTK_DIALOG (dialog)) != GTK_RESPONSE_YES) {
-       /* if not overwrite allow to select another filename */
-       gtk_widget_destroy(dialog);
-       g_free (filename);
-       return;
+        /* if not overwrite allow to select another filename */
+        gtk_widget_destroy(dialog);
+        g_clear_pointer (&filename, g_free);
+        return;
       }
-      gtk_widget_destroy(dialog);
+
+      gtk_widget_destroy (dialog);
     }
 
     index = gtk_combo_box_get_active (GTK_COMBO_BOX(user_data));
-    if (index >= 0)
+    if (index >= 0) {
       persistence_set_integer ("export-filter", index);
+    }
     ef = efilter_by_index (index - 1, NULL);
-    if (!ef)
-      ef = filter_guess_export_filter(filename);
+    if (!ef) {
+      ef = filter_guess_export_filter (filename);
+    }
     if (ef) {
       DiaContext *ctx = dia_context_new (_("Export"));
 
-      g_object_ref(dia->data);
+      g_object_ref (dia->data);
       dia_context_set_filename (ctx, filename);
-      ef->export_func(dia->data, ctx,
-                     filename, dia->filename, ef->user_data);
-      g_object_unref(dia->data);
+      ef->export_func (dia->data,
+                       ctx,
+                       filename,
+                       dia->filename,
+                       ef->user_data);
+      g_object_unref (dia->data);
       dia_context_release (ctx);
-    } else
-      message_error(_("Could not determine which export filter\n"
-                     "to use to save '%s'"), dia_message_filename(filename));
-    g_free (filename);
+    } else {
+      message_error (_("Could not determine which export filter\n"
+                       "to use to save '%s'"),
+                     dia_message_filename (filename));
+    }
+    g_clear_pointer (&filename, g_free);
   }
-  g_object_unref (dia); /* drop our diagram reference */
-  gtk_widget_destroy(exportdlg);
+
+  g_clear_object (&dia); /* drop our diagram reference */
+
+  gtk_widget_destroy (exportdlg);
 }
 
+
 /**
  * React to <Display>/File/Export
  */
@@ -807,28 +824,35 @@ file_export_callback(GtkAction *action)
     g_signal_connect(GTK_FILE_CHOOSER(exportdlg),
                     "response", G_CALLBACK(file_export_response_callback), omenu);
   }
-  if (g_object_get_data (G_OBJECT(exportdlg), "user_data"))
-    g_object_unref (g_object_get_data (G_OBJECT(exportdlg), "user_data"));
-  g_object_ref(dia);
-  g_object_set_data (G_OBJECT (exportdlg), "user_data", dia);
-  gtk_widget_set_sensitive(exportdlg, TRUE);
 
-  if (dia && dia->filename)
+  g_object_set_data_full (G_OBJECT (exportdlg),
+                          "user_data",
+                          g_object_ref (dia),
+                          g_object_unref);
+  gtk_widget_set_sensitive (exportdlg, TRUE);
+
+  if (dia && dia->filename) {
     filename = g_filename_from_utf8(dia->filename, -1, NULL, NULL, NULL);
+  }
+
   if (filename != NULL) {
     char* fnabs = dia_get_absolute_filename (filename);
+
     if (fnabs) {
       char *folder = g_path_get_dirname (fnabs);
       char *basename = g_path_get_basename (fnabs);
+
       /* can't use gtk_file_chooser_set_filename for various reasons, see e.g. bug #305850 */
       gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER(exportdlg), folder);
       export_adapt_extension (basename, persistence_get_integer ("export-filter") - 1);
-      g_free (folder);
-      g_free (basename);
+
+      g_clear_pointer (&folder, g_free);
+      g_clear_pointer (&basename, g_free);
     }
-    g_free(fnabs);
-    g_free(filename);
+
+    g_clear_pointer (&fnabs, g_free);
+    g_clear_pointer (&filename, g_free);
   }
 
-  gtk_widget_show(exportdlg);
+  gtk_widget_show (exportdlg);
 }
diff --git a/app/find-and-replace.c b/app/find-and-replace.c
index f87ff136..fa184559 100644
--- a/app/find-and-replace.c
+++ b/app/find-and-replace.c
@@ -75,14 +75,16 @@ _match_text_prop (DiaObject *obj, const SearchData *sd, const gchar *replacement
 
   /* search part */
   if (sd->flags & MATCH_CASE) {
-    const gchar *p = strstr (*value_to_match, sd->key);
+    const char *p = strstr (*value_to_match, sd->key);
     is_match = p != NULL;
     if (p && replacement) {
-      gchar *a = g_strndup (*value_to_match, p - *value_to_match);
-      gchar *b = g_strdup (p + strlen(sd->key));
+      char *a = g_strndup (*value_to_match, p - *value_to_match);
+      char *b = g_strdup (p + strlen (sd->key));
+
       repl = g_strdup_printf ("%s%s%s", a, replacement, b);
-      g_free (a);
-      g_free (b);
+
+      g_clear_pointer (&a, g_free);
+      g_clear_pointer (&b, g_free);
     }
   } else {
     gchar *s1 = g_utf8_casefold (*value_to_match, -1);
@@ -90,14 +92,17 @@ _match_text_prop (DiaObject *obj, const SearchData *sd, const gchar *replacement
     const gchar *p = strstr (s1, s2);
     is_match = p != NULL;
     if (p && replacement) {
-      gchar *a = g_strndup (*value_to_match, p - s1);
-      gchar *b = g_strdup (*value_to_match + strlen(a) + strlen(sd->key));
+      char *a = g_strndup (*value_to_match, p - s1);
+      char *b = g_strdup (*value_to_match + strlen(a) + strlen(sd->key));
+
       repl = g_strdup_printf ("%s%s%s", a, replacement, b);
-      g_free (a);
-      g_free (b);
+
+      g_clear_pointer (&a, g_free);
+      g_clear_pointer (&b, g_free);
     }
-    g_free (s1);
-    g_free (s2);
+
+    g_clear_pointer (&s1, g_free);
+    g_clear_pointer (&s2, g_free);
   }
 
   if (sd->flags & MATCH_WORD)
@@ -105,10 +110,10 @@ _match_text_prop (DiaObject *obj, const SearchData *sd, const gchar *replacement
 
   /* replace part */
   if (is_match && replacement) {
-    g_free (*value_to_match);
+    g_clear_pointer (&*value_to_match, g_free);
     *value_to_match = repl;
   } else {
-    g_free (repl);
+    g_clear_pointer (&repl, g_free);
   }
 
   return is_match;
@@ -157,8 +162,8 @@ _match_value (gpointer  key,
     gchar *s1 = g_utf8_casefold ((char *)value, -1);
     gchar *s2 = g_utf8_casefold (sd->key, -1);
     gboolean matched = strstr (s1, s2) != NULL;
-    g_free (s1);
-    g_free (s2);
+    g_clear_pointer (&s1, g_free);
+    g_clear_pointer (&s2, g_free);
     return matched;
   }
 }
diff --git a/app/interface.c b/app/interface.c
index 7f86d5a6..58461b91 100644
--- a/app/interface.c
+++ b/app/interface.c
@@ -123,8 +123,8 @@ dia_dnd_file_drag_data_received (GtkWidget        *widget,
             }
           }
 
-          g_free (pFrom);
-          g_free (sPath);
+          g_clear_pointer (&pFrom, g_free);
+          g_clear_pointer (&sPath, g_free);
 
           if (diagram != NULL) {
             diagram_update_extents(diagram);
@@ -252,7 +252,7 @@ zoom_activate_callback (GtkWidget *item, gpointer user_data)
     // Translators: Current zoom level
     zoomamount = g_strdup_printf (_("%f%%"), zoom_amount);
     gtk_entry_set_text (GTK_ENTRY (g_object_get_data (G_OBJECT (ddisp->zoom_status), "user_data")), 
zoomamount);
-    g_free (zoomamount);
+    g_clear_pointer (&zoomamount, g_free);
     magnify = (zoom_amount*DDISPLAY_NORMAL_ZOOM/100.0)/ddisp->zoom_factor;
     if (fabs (magnify - 1.0) > 0.000001) {
       ddisplay_zoom_middle (ddisp, magnify);
@@ -472,12 +472,7 @@ canvas_expose_event (GtkWidget      *widget,
       l = g_slist_next (l);
     }
     /* Free update_areas list: */
-    l = ddisp->update_areas;
-    while (l!=NULL) {
-      g_free (l->data);
-      l = g_slist_next (l);
-    }
-    g_slist_free (ddisp->update_areas);
+    g_slist_free_full (ddisp->update_areas, g_free);
     ddisp->update_areas = NULL;
 
     totrect.left -= 0.1;
@@ -684,7 +679,7 @@ use_integrated_ui_for_display_shell(DDisplay *ddisp, char *title)
   rcstyle = gtk_rc_style_new ();
   rcstyle->xthickness = rcstyle->ythickness = 0;
   gtk_widget_modify_style (close_button, rcstyle);
-  g_object_unref (rcstyle),
+  g_clear_object (&rcstyle);
 
   image = gtk_image_new_from_icon_name ("window-close-symbolic", GTK_ICON_SIZE_MENU);
 
@@ -1454,7 +1449,7 @@ parse_zoom (const char *zoom)
 
   res = g_ascii_strtod (num, NULL);
 
-  g_free (num);
+  g_clear_pointer (&num, g_free);
   g_match_info_free (match_info);
 
   return res * 10;
diff --git a/app/layer-editor/dia-layer-editor-dialog.c b/app/layer-editor/dia-layer-editor-dialog.c
index b5f9f1cb..225846c7 100644
--- a/app/layer-editor/dia-layer-editor-dialog.c
+++ b/app/layer-editor/dia-layer-editor-dialog.c
@@ -195,7 +195,7 @@ diagrams_changed (GListModel *diagrams,
 
     i++;
 
-    g_free (basename);
+    g_clear_pointer (&basename, g_free);
     g_clear_object (&dia);
   }
 
diff --git a/app/layer-editor/layer_dialog.c b/app/layer-editor/layer_dialog.c
index 152ebe38..5a416daa 100644
--- a/app/layer-editor/layer_dialog.c
+++ b/app/layer-editor/layer_dialog.c
@@ -75,7 +75,7 @@ GtkWidget * create_layer_view_widget (void)
   rcstyle = gtk_rc_style_new ();
   rcstyle->xthickness = rcstyle->ythickness = 0;
   gtk_widget_modify_style (hide_button, rcstyle);
-  g_object_unref (rcstyle);
+  g_clear_object (&rcstyle);
 
   image = gtk_image_new_from_icon_name ("window-close-symbolic",
                                         GTK_ICON_SIZE_MENU);
diff --git a/app/load_save.c b/app/load_save.c
index 973582f5..a32bdf94 100644
--- a/app/load_save.c
+++ b/app/load_save.c
@@ -87,16 +87,19 @@ static gboolean diagram_data_save(DiagramData *data, DiaContext *ctx, const char
 
 
 static void
-GHFuncUnknownObjects(gpointer key,
-                     gpointer value,
-                     gpointer user_data)
+GHFuncUnknownObjects (gpointer key,
+                      gpointer value,
+                      gpointer user_data)
 {
-  GString* s = (GString*)user_data;
-  g_string_append(s, "\n");
-  g_string_append(s, (gchar*)key);
-  g_free(key);
+  GString *s = (GString *) user_data;
+
+  g_string_append (s, "\n");
+  g_string_append (s, (char*) key);
+
+  g_free (key);
 }
 
+
 /**
  * Recursive function to read objects from a specific level in the xml.
  *
@@ -337,14 +340,16 @@ read_connections(GList *objects, xmlNodePtr layer_node,
   }
 }
 
+
 static void
-hash_free_string(gpointer       key,
-                gpointer       value,
-                gpointer       user_data)
+hash_free_string (gpointer key,
+                  gpointer value,
+                  gpointer user_data)
 {
-  g_free(key);
+  g_free (key);
 }
 
+
 static xmlNodePtr
 find_node_named (xmlNodePtr p, const char *name)
 {
@@ -467,7 +472,7 @@ diagram_data_load(const gchar *filename, DiagramData *data, DiaContext *ctx, voi
 
     attr = composite_find_attribute(paperinfo, "name");
     if (attr != NULL) {
-      g_free(data->paper.name);
+      g_clear_pointer (&data->paper.name, g_free);
       data->paper.name = data_string(attribute_first_data(attr), ctx);
     }
     if (data->paper.name == NULL || data->paper.name[0] == '\0') {
@@ -1135,7 +1140,7 @@ diagram_data_save(DiagramData *data, DiaContext *ctx, const char *user_filename)
     filename = g_file_read_link(user_filename, &error);
     if (!filename) {
       dia_context_add_message (ctx, "%s", error->message);
-      g_error_free(error);
+      g_clear_error (&error);
       goto CLEANUP;
     }
   }
@@ -1146,7 +1151,7 @@ diagram_data_save(DiagramData *data, DiaContext *ctx, const char *user_filename)
   if (p) {
     *(p+1) = 0;
   } else {
-    g_free(dirname);
+    g_clear_pointer (&dirname, g_free);
     dirname = g_strdup("." G_DIR_SEPARATOR_S);
   }
   tmpname = g_strconcat(dirname,"__diaXXXXXX",NULL);
@@ -1207,10 +1212,10 @@ diagram_data_save(DiagramData *data, DiaContext *ctx, const char *user_filename)
   }
 CLEANUP:
   if (filename != user_filename)
-    g_free(filename);
-  g_free(tmpname);
-  g_free(dirname);
-  g_free(bakname);
+    g_clear_pointer (&filename, g_free);
+  g_clear_pointer (&tmpname, g_free);
+  g_clear_pointer (&dirname, g_free);
+  g_clear_pointer (&bakname, g_free);
   return (ret?FALSE:TRUE);
 }
 
@@ -1249,7 +1254,7 @@ diagram_cleanup_autosave(Diagram *dia)
   if (g_stat(savefile, &statbuf) == 0) { /* Success */
     g_unlink(savefile);
   }
-  g_free(savefile);
+  g_clear_pointer (&savefile, g_free);
   dia->autosavefilename = NULL;
   dia->autosaved = FALSE;
 }
@@ -1278,13 +1283,13 @@ _autosave_in_thread (gpointer data)
   AutoSaveInfo *asi = (AutoSaveInfo *)data;
 
   diagram_data_raw_save(asi->clone, asi->filename, asi->ctx);
-  g_object_unref (asi->clone);
-  g_free (asi->filename);
+  g_clear_object (&asi->clone);
+  g_clear_pointer (&asi->filename, g_free);
   /* FIXME: this is throwing away potential messages ... */
   dia_context_reset (asi->ctx);
   /* ... to avoid creating a message_box within this thread */
   dia_context_release (asi->ctx);
-  g_free (asi);
+  g_clear_pointer (&asi, g_free);
 
   return NULL;
 }
@@ -1308,8 +1313,7 @@ diagram_autosave(Diagram *dia)
         !diagram->autosaved) {
       save_filename = g_strdup_printf ("%s.autosave", dia->filename);
 
-      if (dia->autosavefilename != NULL)
-        g_free(dia->autosavefilename);
+      g_clear_pointer (&dia->autosavefilename, g_free);
 
       dia->autosavefilename = save_filename;
 #ifdef G_THREADS_ENABLED
@@ -1323,7 +1327,7 @@ diagram_autosave(Diagram *dia)
 
         if (!g_thread_try_new ("Autosave", _autosave_in_thread, asi, &error)) {
           message_error ("%s", error->message);
-          g_error_free (error);
+          g_clear_error (&error);
         }
         /* FIXME: need better synchronization */
         dia->autosaved = TRUE;
diff --git a/app/magnify.c b/app/magnify.c
index b931fb3a..1b3d0a04 100644
--- a/app/magnify.c
+++ b/app/magnify.c
@@ -158,9 +158,10 @@ create_magnify_tool(void)
   return (Tool *) tool;
 }
 
+
 void
-free_magnify_tool(Tool *tool)
+free_magnify_tool (Tool *tool)
 {
-  g_free(tool);
-  ddisplay_set_all_cursor(default_cursor);
+  g_clear_pointer (&tool, g_free);
+  ddisplay_set_all_cursor (default_cursor);
 }
diff --git a/app/menus.c b/app/menus.c
index cdf5abbe..369cf582 100644
--- a/app/menus.c
+++ b/app/menus.c
@@ -347,7 +347,7 @@ load_accels (void)
 
   if (accelfilename) {
     gtk_accel_map_load (accelfilename);
-    g_free (accelfilename);
+    g_clear_pointer (&accelfilename, g_free);
   }
 }
 
@@ -557,7 +557,7 @@ ensure_menu_path (GtkUIManager   *ui_manager,
       if (!gtk_action_group_get_action (actions, action_name)) {
         gtk_action_group_add_action (actions, action);
       }
-      g_object_unref (G_OBJECT (action));
+      g_clear_object (&action);
 
       gtk_ui_manager_add_ui (ui_manager,
                              id,
@@ -569,7 +569,7 @@ ensure_menu_path (GtkUIManager   *ui_manager,
     } else {
       g_warning ("ensure_menu_path() invalid menu path: %s.", subpath ? subpath : "NULL");
     }
-    g_free (subpath);
+    g_clear_pointer (&subpath, g_free);
   }
   return id;
 }
@@ -592,13 +592,12 @@ create_integrated_ui_toolbar (void)
   uifile = build_ui_filename ("ui/toolbar-ui.xml");
   if (!gtk_ui_manager_add_ui_from_file (_ui_manager, uifile, &error)) {
     g_critical ("building menus failed: %s", error->message);
-    g_error_free (error);
-    error = NULL;
+    g_clear_error (&error);
     toolbar = GTK_TOOLBAR (gtk_toolbar_new ());
   } else {
     toolbar = GTK_TOOLBAR (gtk_ui_manager_get_widget (_ui_manager, "/Toolbar"));
   }
-  g_free (uifile);
+  g_clear_pointer (&uifile, g_free);
 
   store = gtk_list_store_new (N_COL, G_TYPE_STRING, G_TYPE_DOUBLE);
 
@@ -783,7 +782,7 @@ create_or_ref_tool_actions (void)
         gtk_icon_factory_add (icon_factory, tool_data[i].action_name, is);
         gtk_action_set_stock_id (action, tool_data[i].action_name);
 
-        g_object_unref (pb);
+        g_clear_object (&pb);
       }
     } else {
       g_warning ("couldn't find tool menu item %s", tool_data[i].action_name);
@@ -809,12 +808,11 @@ add_plugin_actions (GtkUIManager *ui_manager, const gchar *base_path)
   actions = gtk_action_group_new (name);
   gtk_action_group_set_translation_domain (actions, NULL);
   gtk_action_group_set_translate_func (actions, _dia_translate, NULL, NULL);
-  g_free (name);
-  name = NULL;
+
+  g_clear_pointer (&name, g_free);
   cnt++;
 
   gtk_ui_manager_insert_action_group (ui_manager, actions, 5 /* "back" */);
-  g_object_unref (actions);
 
   for (cblist = filter_get_callbacks(); cblist; cblist = cblist->next) {
     gchar *menu_path = NULL;
@@ -845,23 +843,28 @@ add_plugin_actions (GtkUIManager *ui_manager, const gchar *base_path)
     }
 
     action = gtk_action_new (cbf->action, gettext (cbf->description), NULL, NULL);
-    g_signal_connect (G_OBJECT (action), "activate",
-                     G_CALLBACK (plugin_callback), (gpointer) cbf);
+    g_signal_connect (G_OBJECT (action),
+                      "activate",
+                      G_CALLBACK (plugin_callback),
+                      (gpointer) cbf);
 
     gtk_action_group_add_action (actions, action);
-    g_object_unref (G_OBJECT (action));
+    g_clear_object (&action);
 
     id = ensure_menu_path (ui_manager, actions, menu_path ? menu_path : cbf->menupath, TRUE);
     gtk_ui_manager_add_ui (ui_manager, id,
-                          menu_path ? menu_path : cbf->menupath,
-                          cbf->description,
-                          cbf->action,
-                          GTK_UI_MANAGER_AUTO,
-                          FALSE);
-    g_free (menu_path);
+                           menu_path ? menu_path : cbf->menupath,
+                           cbf->description,
+                           cbf->action,
+                           GTK_UI_MANAGER_AUTO,
+                           FALSE);
+    g_clear_pointer (&menu_path, g_free);
   }
+
+  g_clear_object (&actions);
 }
 
+
 static void
 _add_stock_icon_name (GtkIconFactory *factory, const char *name, const gchar *icon)
 {
@@ -873,8 +876,8 @@ _add_stock_icon_name (GtkIconFactory *factory, const char *name, const gchar *ic
   pixbuf = pixbuf_from_resource (path);
   set = gtk_icon_set_new_from_pixbuf (pixbuf);
   gtk_icon_factory_add (factory, name, set);
-  g_object_unref (pixbuf);
-  g_free (path);
+  g_clear_object (&pixbuf);
+  g_clear_pointer (&path, g_free);
   pixbuf = NULL;
 }
 
@@ -895,8 +898,7 @@ register_stock_icons (void)
   _add_stock_icon_name (factory, DIA_STOCK_LAYERS, "dia-layers");
 
   gtk_icon_factory_add_default (factory);
-  g_object_unref (factory);
-  factory = NULL;
+  g_clear_object (&factory);
 }
 
 gchar*
@@ -923,9 +925,9 @@ builder_new_from_file (const char *filename)
   uifile = build_ui_filename (filename);
   if (!gtk_builder_add_from_file (builder, uifile, &error)) {
     g_warning ("Couldn't load builder file: %s", error->message);
-    g_error_free (error);
+    g_clear_error (&error);
   }
-  g_free (uifile);
+  g_clear_pointer (&uifile, g_free);
   return builder;
 }
 
@@ -946,7 +948,7 @@ _ui_manager_connect_proxy (GtkUIManager *manager,
 
     if (tooltip) {
       gtk_widget_set_tooltip_text (proxy, tooltip);
-      g_free (tooltip);
+      g_clear_pointer (&tooltip, g_free);
     }
   }
 }
@@ -1057,10 +1059,9 @@ menus_init(void)
   uifile = build_ui_filename ("ui/toolbox-ui.xml");
   if (!gtk_ui_manager_add_ui_from_file (_ui_manager, uifile, &error)) {
     g_warning ("building menus failed: %s", error->message);
-    g_error_free (error);
-    error = NULL;
+    g_clear_error (&error);
   }
-  g_free (uifile);
+  g_clear_pointer (&uifile, g_free);
 
   /* the display menu */
   display_actions = create_or_ref_display_actions (TRUE);
@@ -1074,8 +1075,7 @@ menus_init(void)
   gtk_ui_manager_insert_action_group (display_ui_manager, tool_actions, 0);
   if (!gtk_ui_manager_add_ui_from_string (display_ui_manager, ui_info, -1, &error)) {
     g_warning ("built-in menus failed: %s", error->message);
-    g_error_free (error);
-    error = NULL;
+    g_clear_error (&error);
   }
 
   uifile = build_ui_filename ("ui/popup-ui.xml");
@@ -1083,10 +1083,9 @@ menus_init(void)
    * menu hierarchy and merge it into a popup somehow. */
   if (!gtk_ui_manager_add_ui_from_file (display_ui_manager, uifile, &error)) {
     g_warning ("building menus failed: %s", error->message);
-    g_error_free (error);
-    error = NULL;
+    g_clear_error (&error);
   }
-  g_free (uifile);
+  g_clear_pointer (&uifile, g_free);
 
   display_accels = gtk_ui_manager_get_accel_group (display_ui_manager);
   display_menubar = gtk_ui_manager_get_widget (display_ui_manager, DISPLAY_MENU);
@@ -1127,14 +1126,13 @@ menus_get_integrated_ui_menubar (GtkWidget     **menubar,
   uifile = build_ui_filename ("ui/integrated-ui.xml");
   if (!gtk_ui_manager_add_ui_from_file (_ui_manager, uifile, &error)) {
     g_warning ("building integrated ui menus failed: %s", error->message);
-    g_error_free (error);
-    error = NULL;
+    g_clear_error (&error);
   }
-  g_free (uifile);
+  g_clear_pointer (&uifile, g_free);
+
   if (!gtk_ui_manager_add_ui_from_string (_ui_manager, ui_info, -1, &error)) {
     g_warning ("built-in menus failed: %s", error->message);
-    g_error_free (error);
-    error = NULL;
+    g_clear_error (&error);
   }
 
   add_plugin_actions (_ui_manager, NULL);
@@ -1198,16 +1196,16 @@ menus_create_display_menubar (GtkUIManager   **ui_manager,
   *ui_manager = gtk_ui_manager_new ();
   gtk_ui_manager_insert_action_group (*ui_manager, *actions, 0);
   gtk_ui_manager_insert_action_group (*ui_manager, tool_actions, 0);
-  g_object_unref (G_OBJECT (tool_actions));
+  g_clear_object (&tool_actions);
 
   uifile = build_ui_filename ("ui/display-ui.xml");
   if (!gtk_ui_manager_add_ui_from_file (*ui_manager, uifile, &error)) {
     g_warning ("building menus failed: %s", error->message);
-    g_error_free (error);
-    g_free (uifile);
+    g_clear_error (&error);
+    g_clear_pointer (&uifile, g_free);
     return NULL;
   }
-  g_free (uifile);
+  g_clear_pointer (&uifile, g_free);
 
   add_plugin_actions (*ui_manager, DISPLAY_MENU);
   menu_bar = gtk_ui_manager_get_widget (*ui_manager, DISPLAY_MENU);
@@ -1330,8 +1328,7 @@ menus_clear_recent (void)
 
   if (recent_actions) {
     gtk_ui_manager_remove_action_group (_ui_manager, recent_actions);
-    g_object_unref (G_OBJECT (recent_actions));
-    recent_actions = NULL;
+    g_clear_object (&recent_actions);
   }
 }
 
@@ -1371,7 +1368,7 @@ plugin_callback (GtkWidget *widget, gpointer data)
       } else { /* no diagram to keep the change, throw it away */
         if (change->free)
           change->free(change);
-        g_free(change);
+        g_clear_pointer (&change, g_free);
       }
     }
   }
diff --git a/app/modify_tool.c b/app/modify_tool.c
index 815ea8d4..96c1f6b9 100644
--- a/app/modify_tool.c
+++ b/app/modify_tool.c
@@ -154,14 +154,14 @@ gdk_event_to_dia_ModifierKeys(guint event_state)
 
 
 void
-free_modify_tool(Tool *tool)
+free_modify_tool (Tool *tool)
 {
   ModifyTool *mtool = (ModifyTool *)tool;
-  if (mtool->gc)
-    g_object_unref(mtool->gc);
-  g_free(mtool);
+  g_clear_object (&mtool->gc);
+  g_clear_pointer (&mtool, g_free);
 }
 
+
 static DiaObject *
 click_select_object(DDisplay *ddisp, Point *clickedpoint,
                    GdkEventButton *event)
@@ -559,7 +559,7 @@ modify_motion (ModifyTool     *tool,
       gtk_statusbar_pop (statusbar, context_id);
       gtk_statusbar_push (statusbar, context_id, postext);
 
-      g_free(postext);
+      g_clear_pointer (&postext, g_free);
     }
 
     diagram_update_connections_selection(ddisp->diagram);
@@ -645,10 +645,10 @@ modify_motion (ModifyTool     *tool,
       gtk_statusbar_pop (statusbar, context_id);
       gtk_statusbar_push (statusbar, context_id, postext);
 
-      g_free(postext);
+      g_clear_pointer (&postext, g_free);
     }
 
-    object_add_updates(tool->object, ddisp->diagram);
+    object_add_updates (tool->object, ddisp->diagram);
 
     /* Handle undo */
     if (tool->object)
@@ -807,10 +807,7 @@ modify_button_release(ModifyTool *tool, GdkEventButton *event,
 
     undo_set_transactionpoint(ddisp->diagram->undo);
 
-    if (tool->orig_pos != NULL) {
-      g_free(tool->orig_pos);
-      tool->orig_pos = NULL;
-    }
+    g_clear_pointer (&tool->orig_pos, g_free);
 
     break;
   case STATE_BOX_SELECT:
diff --git a/app/navigation.c b/app/navigation.c
index baf1fc98..4670555f 100644
--- a/app/navigation.c
+++ b/app/navigation.c
@@ -125,12 +125,11 @@ navigation_popup_new (DDisplay *ddisp)
                                                  nav_xpm);
 
   image = gtk_image_new_from_pixmap (pixmap, mask);
-  g_object_unref(pixmap);
-  g_object_unref(mask);
+  g_clear_object (&pixmap);
+  g_clear_object (&mask);
 
   gtk_container_add (GTK_CONTAINER (button), image);
-  gtk_widget_show(image);
-
+  gtk_widget_show (image);
 
   return button;
 }
@@ -247,7 +246,7 @@ on_button_navigation_popup_pressed (GtkButton * button, gpointer _ddisp)
 
     bitmap = gdk_bitmap_create_from_data(NULL, cursor_none_data, 1, 1);
     nav->cursor = gdk_cursor_new_from_pixmap(bitmap, bitmap, &fg, &bg, 1, 1);
-    g_object_unref(bitmap);
+    g_clear_object (&bitmap);
   }
 
   /*grab the pointer*/
@@ -261,14 +260,14 @@ on_button_navigation_popup_pressed (GtkButton * button, gpointer _ddisp)
   nav->surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32,
                                             nav->width, nav->height);
 
-  renderer = g_object_new (g_type_from_name ("DiaCairoRenderer"), NULL);
+  renderer = g_object_new (DIA_CAIRO_TYPE_RENDERER, NULL);
   renderer->scale = zoom;
   renderer->surface = cairo_surface_reference (nav->surface);
 
   /*render the data*/
   data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
 
-  g_object_unref (renderer);
+  g_clear_object (&renderer);
 
   nav->is_first_expose = TRUE;/*set to request to draw the miniframe*/
 }
diff --git a/app/object_ops.c b/app/object_ops.c
index db0af861..3a7489da 100644
--- a/app/object_ops.c
+++ b/app/object_ops.c
@@ -275,7 +275,7 @@ object_list_align_v(GList *objects, Diagram *dia, int align)
    * to sort them out by position.
    */
   if (align == DIA_ALIGN_EQUAL || align == DIA_ALIGN_ADJACENT) {
-    DiaObject **object_array = (DiaObject **) g_malloc (sizeof (DiaObject *) * nobjs);
+    DiaObject **object_array = g_new0 (DiaObject *, nobjs);
     int j = 0;
 
     list = objects;
@@ -295,7 +295,7 @@ object_list_align_v(GList *objects, Diagram *dia, int align)
 
     g_list_free (unconnected);
     objects = unconnected = list;
-    g_free (object_array);
+    g_clear_pointer (&object_array, g_free);
   }
 
   switch (align) {
@@ -438,7 +438,7 @@ object_list_align_h(GList *objects, Diagram *dia, int align)
    * to sort them out by position.
    */
   if (align == DIA_ALIGN_EQUAL || align == DIA_ALIGN_ADJACENT) {
-    DiaObject **object_array = (DiaObject **)g_malloc(sizeof(DiaObject*)*nobjs);
+    DiaObject **object_array = g_new0 (DiaObject *, nobjs);
     int j = 0;
 
     list = objects;
@@ -456,7 +456,7 @@ object_list_align_h(GList *objects, Diagram *dia, int align)
     g_assert (objects == unconnected);
     g_list_free (unconnected);
     objects = unconnected = list;
-    g_free(object_array);
+    g_clear_pointer (&object_array, g_free);
   }
 
   switch (align) {
diff --git a/app/pagesetup.c b/app/pagesetup.c
index 20e20cd1..e5766cc1 100644
--- a/app/pagesetup.c
+++ b/app/pagesetup.c
@@ -41,27 +41,30 @@ struct _PageSetup {
 static void pagesetup_changed  (GtkWidget *wid, PageSetup *ps);
 static void pagesetup_apply    (GtkWidget *wid, PageSetup *ps);
 
-static gint
-pagesetup_respond(GtkWidget *widget,
-                   gint       response_id,
+
+static int
+pagesetup_respond (GtkWidget *widget,
+                   int        response_id,
                    gpointer   data)
 {
   PageSetup *ps = (PageSetup *)data;
 
   if (   response_id == GTK_RESPONSE_APPLY
       || response_id == GTK_RESPONSE_OK) {
-    if (ps->changed)
-      pagesetup_apply(widget, ps);
+    if (ps->changed) {
+      pagesetup_apply (widget, ps);
+    }
   }
 
   if (response_id != GTK_RESPONSE_APPLY) {
-    g_object_unref(ps->dia);
+    g_object_unref (&ps->dia);
     gtk_widget_destroy(ps->window);
   }
 
   return 0;
 }
 
+
 void
 create_page_setup_dlg(Diagram *dia)
 {
@@ -169,15 +172,15 @@ pagesetup_apply(GtkWidget *wid, PageSetup *ps)
   dia_mem_swap_change_new (ps->dia, &ps->dia->data->paper, sizeof(ps->dia->data->paper));
   undo_set_transactionpoint(ps->dia->undo);
 
-  g_free(ps->dia->data->paper.name);
+  g_clear_pointer (&ps->dia->data->paper.name, g_free);
   ps->dia->data->paper.name =
-    g_strdup(dia_page_layout_get_paper(DIA_PAGE_LAYOUT(ps->paper)));
+    g_strdup (dia_page_layout_get_paper (DIA_PAGE_LAYOUT (ps->paper)));
 
-  dia_page_layout_get_margins(DIA_PAGE_LAYOUT(ps->paper),
-                             &ps->dia->data->paper.tmargin,
-                             &ps->dia->data->paper.bmargin,
-                             &ps->dia->data->paper.lmargin,
-                             &ps->dia->data->paper.rmargin);
+  dia_page_layout_get_margins (DIA_PAGE_LAYOUT (ps->paper),
+                               &ps->dia->data->paper.tmargin,
+                               &ps->dia->data->paper.bmargin,
+                               &ps->dia->data->paper.lmargin,
+                               &ps->dia->data->paper.rmargin);
 
   ps->dia->data->paper.is_portrait =
     dia_page_layout_get_orientation(DIA_PAGE_LAYOUT(ps->paper)) ==
diff --git a/app/properties-dialog.c b/app/properties-dialog.c
index 4ad95592..3efcf7f1 100644
--- a/app/properties-dialog.c
+++ b/app/properties-dialog.c
@@ -239,13 +239,13 @@ object_list_properties_show(Diagram *dia, GList *objects)
 
   if (one_obj) {
     DiaObjectType *otype = one_obj->type;
-    gchar *buf;
+    char *buf;
 
-    buf = g_strconcat(_("Properties: "), _(otype->name), NULL);
-    gtk_window_set_title(GTK_WINDOW(dialog), buf);
-    g_free(buf);
+    buf = g_strconcat (_("Properties: "), _(otype->name), NULL);
+    gtk_window_set_title (GTK_WINDOW (dialog), buf);
+    g_clear_pointer (&buf, g_free);
   } else {
-    gtk_window_set_title(GTK_WINDOW(dialog), _("Object properties:"));
+    gtk_window_set_title (GTK_WINDOW (dialog), _("Object properties:"));
   }
 
   g_signal_connect (G_OBJECT (properties), "destroy",
diff --git a/app/recent_files.c b/app/recent_files.c
index d8dccecc..8f366ce9 100644
--- a/app/recent_files.c
+++ b/app/recent_files.c
@@ -88,33 +88,43 @@ recent_file_history_make_menu (void)
 
     gtk_action_group_add_action_with_accel (group, action, accel);
 
-    g_free (name);
-    g_free (file);
+    g_clear_pointer (&name, g_free);
+    g_clear_pointer (&file, g_free);
     g_strfreev (split);
-    g_free (file_escaped);
-    g_free (label);
-    g_free (accel);
+    g_clear_pointer (&file_escaped, g_free);
+    g_clear_pointer (&label, g_free);
+    g_clear_pointer (&accel, g_free);
   }
   menus_set_recent (group);
 }
 
-/** Add a new item to the file history list.
+
+/**
+ * recent_file_history_add:
+ * @fname: filename to add
+ *
+ * Add a new item to the file history list.
  * Can also handle the addition of an already exisiting file. The whole recent menu is rebuild every time but
  * it should be fast enough to favor simplicity of the code.
+ *
+ * Since: dawn-of-time
  */
 void
-recent_file_history_add(const char *fname)
+recent_file_history_add (const char *fname)
 {
-  gchar *absname = dia_get_absolute_filename(fname);
-  gchar *filename = g_filename_to_utf8(absname, -1, NULL, NULL, NULL);
-  recent_file_history_clear_menu();
-  persistent_list_add("recent-files", filename);
-  g_free(absname);
-  g_free(filename);
+  char *absname = dia_get_absolute_filename (fname);
+  char *filename = g_filename_to_utf8 (absname, -1, NULL, NULL, NULL);
 
-  recent_file_history_make_menu();
+  recent_file_history_clear_menu ();
+  persistent_list_add ("recent-files", filename);
+
+  g_clear_pointer (&absname, g_free);
+  g_clear_pointer (&filename, g_free);
+
+  recent_file_history_make_menu ();
 }
 
+
 /* load the recent file history */
 void
 recent_file_history_init (void)
@@ -126,23 +136,34 @@ recent_file_history_init (void)
   recent_file_history_make_menu();
 }
 
-/* remove a broken file from the history and update menu accordingly
- * Xing Wang, 2002.06 */
+
+/**
+ * recent_file_history_remove:
+ * @fname: filename to remove
+ *
+ * Remove a broken file from the history and update menu accordingly
+ *
+ * Xing Wang, 2002.06
+ *
+ * Since: dawn-of-time
+ */
 void
 recent_file_history_remove (const char *fname)
 {
-  gchar *absname = dia_get_absolute_filename(fname);
-  gchar *filename = g_filename_to_utf8(absname, -1, NULL, NULL, NULL);
+  char *absname = dia_get_absolute_filename (fname);
+  char *filename = g_filename_to_utf8 (absname, -1, NULL, NULL, NULL);
 
   recent_file_history_clear_menu();
 
   persistent_list_remove("recent-files", filename);
-  g_free(absname);
-  g_free(filename);
 
-  recent_file_history_make_menu();
+  g_clear_pointer (&absname, g_free);
+  g_clear_pointer (&filename, g_free);
+
+  recent_file_history_make_menu ();
 }
 
+
 static void
 open_recent_file_callback(GtkWidget *widget, gpointer data)
 {
@@ -159,7 +180,9 @@ open_recent_file_callback(GtkWidget *widget, gpointer data)
     if (diagram->displays == NULL) {
       new_display(diagram);
     }
-  } else
+  } else {
     recent_file_history_remove (filename);
-  g_free(filename);
+  }
+
+  g_clear_pointer (&filename, g_free);
 }
diff --git a/app/ruler.c b/app/ruler.c
index f56b332f..c5c127d4 100644
--- a/app/ruler.c
+++ b/app/ruler.c
@@ -119,7 +119,9 @@ dia_ruler_draw (GtkWidget *widget,
         cairo_restore (cr);
       }
     }
-    g_object_unref (layout);
+
+    g_clear_object (&layout);
+
     /* arrow */
     if (ruler->position > ruler->lower && ruler->position < ruler->upper) {
       real r_pos = ruler->position;
@@ -237,13 +239,14 @@ dia_ruler_new (GtkOrientation orientation, GtkWidget *shell, DDisplay *ddisp)
   GtkWidget *rule = g_object_new (DIA_TYPE_RULER, NULL);
   /* calculate from style settings  */
   PangoLayout *layout = gtk_widget_create_pango_layout (shell, "X");
-  gint height;
+  int height;
+
   pango_layout_get_pixel_size (layout, NULL, &height);
   gtk_widget_set_size_request (rule, height, height);
-  g_object_unref (layout);
+  g_clear_object (&layout);
 
-  DIA_RULER(rule)->orientation = orientation;
-  DIA_RULER(rule)->ddisp = ddisp;
+  DIA_RULER (rule)->orientation = orientation;
+  DIA_RULER (rule)->ddisp = ddisp;
 
   gtk_widget_set_events (rule, GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | 
GDK_POINTER_MOTION_MASK);
 
diff --git a/app/scroll_tool.c b/app/scroll_tool.c
index 0dbf24ed..7259a044 100644
--- a/app/scroll_tool.c
+++ b/app/scroll_tool.c
@@ -53,14 +53,15 @@ create_scroll_tool(void)
   return (Tool *)tool;
 }
 
+
 void
-free_scroll_tool(Tool *tool)
+free_scroll_tool (Tool *tool)
 {
-  g_free(tool);
-  ddisplay_set_all_cursor(default_cursor);
-
+  g_clear_pointer (&tool, g_free);
+  ddisplay_set_all_cursor (default_cursor);
 }
 
+
 static void
 scroll_double_click(ScrollTool *tool, GdkEventButton *event,
                    DDisplay *ddisp)
diff --git a/app/sheet-editor/sheets.c b/app/sheet-editor/sheets.c
index ade3d933..cbd310e6 100644
--- a/app/sheet-editor/sheets.c
+++ b/app/sheet-editor/sheets.c
@@ -135,7 +135,7 @@ find_sheet (GtkTreeModel *model,
     gtk_combo_box_set_active_iter (GTK_COMBO_BOX (data->combo), iter);
   }
 
-  g_free (item);
+  g_clear_pointer (&item, g_free);
 
   return res;
 }
@@ -345,14 +345,15 @@ create_object_pixmap (SheetObject  *so,
       pixbuf = pixbuf_from_resource (((char *) so->pixmap) + 4);
 
       gdk_pixbuf_render_pixmap_and_mask (pixbuf, pixmap, mask, 1.0);
-      g_object_unref (pixbuf);
+
+      g_clear_object (&pixbuf);
     } else {
       *pixmap =
         gdk_pixmap_colormap_create_from_xpm_d (NULL,
-                                                gtk_widget_get_colormap (parent),
-                                                mask,
-                                                &style->bg[GTK_STATE_NORMAL],
-                                                (gchar **) so->pixmap);
+                                               gtk_widget_get_colormap (parent),
+                                               mask,
+                                               &style->bg[GTK_STATE_NORMAL],
+                                               (char **) so->pixmap);
     }
   } else {
     if (so->pixmap_file != NULL) {
@@ -371,14 +372,14 @@ create_object_pixmap (SheetObject  *so,
                                               height > 22 ? (height - 22) / 2 : 0,
                                               22,
                                               height > 22 ? 22 : height);
-          g_object_unref (pixbuf);
+          g_clear_object (&pixbuf);
           pixbuf = cropped;
         }
         gdk_pixbuf_render_pixmap_and_mask (pixbuf, pixmap, mask, 1.0);
-        g_object_unref (pixbuf);
+        g_clear_object (&pixbuf);
       } else {
         message_warning ("%s", error->message);
-        g_error_free (error);
+        g_clear_error (&error);
         *pixmap = gdk_pixmap_colormap_create_from_xpm_d (NULL,
                                                          gtk_widget_get_colormap (parent),
                                                          mask,
diff --git a/app/sheet-editor/sheets_dialog.c b/app/sheet-editor/sheets_dialog.c
index 08dfb1b5..ea7a9aa9 100644
--- a/app/sheet-editor/sheets_dialog.c
+++ b/app/sheet-editor/sheets_dialog.c
@@ -41,16 +41,18 @@
 #include "persistence.h"
 #include "menus.h"
 
+
 static void
 sheets_dialog_destroyed (GtkWidget *widget, gpointer user_data)
 {
   GObject *builder = g_object_get_data (G_OBJECT (widget), "_sheet_dialogs_builder");
-  if (builder) {
-    g_object_unref (builder);
-  }
+
+  g_clear_object (&builder);
+
   g_object_set_data (G_OBJECT (widget), "_sheet_dialogs_builder", NULL);
 }
 
+
 GtkWidget*
 create_sheets_main_dialog (void)
 {
diff --git a/app/sheet-editor/sheets_dialog_callbacks.c b/app/sheet-editor/sheets_dialog_callbacks.c
index 8b6723bc..2791eeab 100644
--- a/app/sheet-editor/sheets_dialog_callbacks.c
+++ b/app/sheet-editor/sheets_dialog_callbacks.c
@@ -305,7 +305,7 @@ sheets_dialog_object_set_tooltip (SheetObjectMod *som, GtkWidget *button)
   }
 
   gtk_widget_set_tooltip_text (button, tip);
-  g_free (tip);
+  g_clear_pointer (&tip, g_free);
 }
 
 static GtkWidget *
@@ -754,14 +754,14 @@ on_sheets_new_dialog_button_ok_clicked (GtkButton       *button,
       if (strcmp (p, ".shape")) {
         message_error (_("Filename must end with '%s': '%s'"),
                        ".shape", dia_message_filename (file_name));
-        g_free (file_name);
+        g_clear_pointer (&file_name, g_free);
         return;
       }
 
       if (g_stat (file_name, &stat_buf) == -1) {
         message_error (_("Error examining %s: %s"),
                          dia_message_filename (file_name), strerror (errno));
-        g_free (file_name);
+        g_clear_pointer (&file_name, g_free);
         return;
       }
 
@@ -793,7 +793,7 @@ on_sheets_new_dialog_button_ok_clicked (GtkButton       *button,
         }
         message_error (_("Could not interpret shape file: '%s'"),
                         dia_message_filename (file_name));
-        g_free(file_name);
+        g_clear_pointer (&file_name, g_free);
         return;
       }
       object_register_type (ot);
@@ -1558,21 +1558,21 @@ write_user_sheet (Sheet *sheet)
     basename = g_strdelimit (basename, G_STR_DELIMITERS G_DIR_SEPARATOR_S, '_');
     filename = g_strdup_printf ("%s%s%s.sheet", dir_user_sheets,
                                 G_DIR_SEPARATOR_S, basename);
-    g_free (basename);
+    g_clear_pointer (&basename, g_free);
   } else {
     gchar *basename;
 
     basename = g_path_get_basename (sheet->filename);
     filename = g_strdup_printf ("%s%s%s", dir_user_sheets,
                                 G_DIR_SEPARATOR_S, basename);
-    g_free (basename);
+    g_clear_pointer (&basename, g_free);
   }
   file = g_fopen (filename, "w");
 
   if (file == NULL) {
     message_error (_("Couldn't open: '%s' for writing"),
                    dia_message_filename(filename));
-    g_free(filename);
+    g_clear_pointer (&filename, g_free);
     return FALSE;
   }
   fclose (file);
@@ -1643,17 +1643,17 @@ write_user_sheet (Sheet *sheet)
 
       basename = g_path_get_basename (som->svg_filename);
       dest = g_strdup_printf ("%s%s%s", dia_user_shapes, G_DIR_SEPARATOR_S, basename);
-      g_free (basename);
+      g_clear_pointer (&basename, g_free);
       copy_file (som->svg_filename, dest);
-      g_free (dest);
+      g_clear_pointer (&dest, g_free);
 
       /* avoid crashing when there is no icon */
       if (som->sheet_object.pixmap_file) {
         basename = g_path_get_basename (som->sheet_object.pixmap_file);
         dest = g_strdup_printf ("%s%s%s", dia_user_shapes, G_DIR_SEPARATOR_S, basename);
-        g_free (basename);
+        g_clear_pointer (&basename, g_free);
         copy_file (som->sheet_object.pixmap_file, dest);
-        g_free (dest);
+        g_clear_pointer (&dest, g_free);
       }
     }
 
@@ -1667,7 +1667,7 @@ write_user_sheet (Sheet *sheet)
 
       user_data = g_strdup_printf ("%u", GPOINTER_TO_UINT (sheetobject->user_data));
       xmlSetProp (object_node, (const xmlChar *) "intdata", (xmlChar *) user_data);
-      g_free (user_data);
+      g_clear_pointer (&user_data, g_free);
     }
 
     xmlAddChild (object_node, xmlNewText ((const xmlChar *) "\n"));
@@ -1695,9 +1695,9 @@ write_user_sheet (Sheet *sheet)
       }
       xmlAddChild (icon_node, xmlNewText ((xmlChar *) icon));
       xmlAddChild (object_node, xmlNewText ((const xmlChar *) "\n"));
-      g_free (canonical_icon);
-      g_free (canonical_user_sheets);
-      g_free (canonical_sheets);
+      g_clear_pointer (&canonical_icon, g_free);
+      g_clear_pointer (&canonical_user_sheets, g_free);
+      g_clear_pointer (&canonical_sheets, g_free);
     }
   }
   xmlSetDocCompressMode (doc, 0);
diff --git a/app/textedit_tool.c b/app/textedit_tool.c
index 00bbb885..af8af403 100644
--- a/app/textedit_tool.c
+++ b/app/textedit_tool.c
@@ -157,6 +157,7 @@ create_textedit_tool(void)
   return (Tool *)tool;
 }
 
+
 void
 free_textedit_tool (Tool *tool)
 {
@@ -167,5 +168,5 @@ free_textedit_tool (Tool *tool)
   }
   ddisplay_set_all_cursor(default_cursor);
 
-  g_free (tool);
+  g_clear_pointer (&tool, g_free);
 }
diff --git a/app/toolbox.c b/app/toolbox.c
index c60385e7..e1aa44b5 100644
--- a/app/toolbox.c
+++ b/app/toolbox.c
@@ -315,22 +315,26 @@ fill_sheet_wbox(Sheet *sheet)
 
       pixbuf = gdk_pixbuf_new_from_file(sheet_obj->pixmap_file, &gerror);
       if (pixbuf != NULL) {
-          int width = gdk_pixbuf_get_width (pixbuf);
-          int height = gdk_pixbuf_get_height (pixbuf);
-          if (width > 22 && prefs.fixed_icon_size) {
-           GdkPixbuf *cropped;
-           g_warning ("Shape icon '%s' size wrong, cropped.", sheet_obj->pixmap_file);
-           cropped = gdk_pixbuf_new_subpixbuf (pixbuf,
-                                              (width - 22) / 2, height > 22 ? (height - 22) / 2 : 0,
-                                              22, height > 22 ? 22 : height);
-           g_object_unref (pixbuf);
-           pixbuf = cropped;
-         }
+        int width = gdk_pixbuf_get_width (pixbuf);
+        int height = gdk_pixbuf_get_height (pixbuf);
+        if (width > 22 && prefs.fixed_icon_size) {
+          GdkPixbuf *cropped;
+          g_warning ("Shape icon '%s' size wrong, cropped.",
+                     sheet_obj->pixmap_file);
+          cropped = gdk_pixbuf_new_subpixbuf (pixbuf,
+                                              (width - 22) / 2,
+                                              height > 22 ? (height - 22) / 2 : 0,
+                                              22,
+                                              height > 22 ? 22 : height);
+          g_clear_object (&pixbuf);
+          pixbuf = cropped;
+        }
       } else {
-          pixbuf = gdk_pixbuf_new_from_xpm_data (missing);
+        pixbuf = gdk_pixbuf_new_from_xpm_data (missing);
 
-          message_warning("failed to load icon for file\n %s\n cause=%s",
-                          sheet_obj->pixmap_file,gerror?gerror->message:"[NULL]");
+        message_warning ("failed to load icon for file\n %s\n cause=%s",
+                         sheet_obj->pixmap_file,
+                         gerror ? gerror->message : "[NULL]");
       }
     } else {
       DiaObjectType *type;
@@ -370,10 +374,10 @@ fill_sheet_wbox(Sheet *sheet)
     g_signal_connect (G_OBJECT (button), "button_press_event",
                      G_CALLBACK (tool_button_press), data);
 
-    tool_setup_drag_source(button, data, pixbuf);
-    g_object_unref(pixbuf);
+    tool_setup_drag_source (button, data, pixbuf);
+    g_clear_object (&pixbuf);
 
-    gtk_widget_set_tooltip_text (button, gettext(sheet_obj->description));
+    gtk_widget_set_tooltip_text (button, gettext (sheet_obj->description));
   }
   /* If the selection is in the old sheet, steal it */
   if (active_tool != NULL &&
@@ -424,7 +428,7 @@ set_sheet (GtkTreeModel *model,
     gtk_combo_box_set_active_iter (GTK_COMBO_BOX (sheet_menu.combo), iter);
   }
 
-  g_free (sheet);
+  g_clear_pointer (&sheet, g_free);
 
   return res;
 }
@@ -513,7 +517,7 @@ sheet_changed (GtkComboBox *widget, gpointer user_data)
         fill_sheet_wbox (sheet);
       }
 
-      g_free (name);
+      g_clear_pointer (&name, g_free);
       break;
     case SPECIAL_RESET:
       persistent_list_clear (SHEET_PERSIST_NAME);
@@ -707,15 +711,19 @@ create_sheet_dropdown_menu(GtkWidget *parent)
   gtk_widget_show (sheet_menu.combo);
 }
 
+
 void
-fill_sheet_menu(void)
+fill_sheet_menu (void)
 {
-  gchar *selection = get_current_sheet ();
+  char *selection = get_current_sheet ();
+
   create_sheet_dropdown_menu (gtk_widget_get_parent (sheet_menu.combo));
   set_current_sheet (selection);
-  g_free(selection);
+
+  g_clear_pointer (&selection, g_free);
 }
 
+
 static void
 create_sheets(GtkWidget *parent)
 {
@@ -756,7 +764,7 @@ create_sheets(GtkWidget *parent)
     fill_sheet_wbox(sheet);
     set_current_sheet (sheetname);
   }
-  g_free(sheetname);
+  g_clear_pointer (&sheetname, g_free);
 }
 
 static void
@@ -841,7 +849,7 @@ create_lineprops_area(GtkWidget *parent)
   arrow.length = persistence_register_real("start-arrow-length", DEFAULT_ARROW_LENGTH);
   arrow_name = persistence_register_string("start-arrow-type", "None");
   arrow.type = arrow_type_from_name(arrow_name);
-  g_free(arrow_name);
+  g_clear_pointer (&arrow_name, g_free);
   dia_arrow_chooser_set_arrow(DIA_ARROW_CHOOSER(chooser), &arrow);
   attributes_set_default_start_arrow(arrow);
   gtk_widget_set_tooltip_text(chooser, _("Arrow style at the beginning of new lines.  Click to pick an 
arrow, or set arrow parameters with Details…"));
@@ -860,7 +868,7 @@ create_lineprops_area(GtkWidget *parent)
   arrow.length = persistence_register_real("end-arrow-length", DEFAULT_ARROW_LENGTH);
   arrow_name = persistence_register_string("end-arrow-type", "Filled Concave");
   arrow.type = arrow_type_from_name(arrow_name);
-  g_free(arrow_name);
+  g_clear_pointer (&arrow_name, g_free);
   dia_arrow_chooser_set_arrow(DIA_ARROW_CHOOSER(chooser), &arrow);
   attributes_set_default_end_arrow(arrow);
 
@@ -904,7 +912,7 @@ tool_get_pixbuf (ToolButton *tb)
   } else {
     path = g_strdup_printf ("/org/gnome/Dia/icons/%s.png", tb->icon_name);
     pixbuf = pixbuf_from_resource (path);
-    g_free (path);
+    g_clear_pointer (&path, g_free);
   }
 
   return pixbuf;
@@ -951,27 +959,29 @@ create_tools(GtkWidget *parent)
     if (tool_data[i].callback_data.type == CREATE_OBJECT_TOOL)
       tool_setup_drag_source(button, &tool_data[i].callback_data, pixbuf);
 
-    if (pixbuf)
-      g_object_unref(pixbuf);
+    g_clear_object (&pixbuf);
 
     tool_data[i].callback_data.widget = button;
 
     if (tool_data[i].tool_accelerator) {
-       guint key;
-       GdkModifierType mods;
-       gchar *alabel, *atip;
-
-       gtk_accelerator_parse (tool_data[i].tool_accelerator, &key, &mods);
-
-       alabel = gtk_accelerator_get_label(key, mods);
-       atip = g_strconcat(gettext(tool_data[i].tool_desc), " (", alabel, ")", NULL);
-       gtk_widget_set_tooltip_text (button, atip);
-       g_free (atip);
-       g_free (alabel);
-
+      guint key;
+      GdkModifierType mods;
+      char *alabel, *atip;
+
+      gtk_accelerator_parse (tool_data[i].tool_accelerator, &key, &mods);
+
+      alabel = gtk_accelerator_get_label (key, mods);
+      atip = g_strconcat (gettext (tool_data[i].tool_desc),
+                          " (",
+                          alabel,
+                          ")",
+                          NULL);
+      gtk_widget_set_tooltip_text (button, atip);
+
+      g_clear_pointer (&atip, g_free);
+      g_clear_pointer (&alabel, g_free);
     } else {
-       gtk_widget_set_tooltip_text (button,
-                               gettext(tool_data[i].tool_desc));
+      gtk_widget_set_tooltip_text (button, gettext (tool_data[i].tool_desc));
     }
 
     gtk_widget_show (image);
diff --git a/app/undo.c b/app/undo.c
index 0eabadda..78af391a 100644
--- a/app/undo.c
+++ b/app/undo.c
@@ -89,14 +89,16 @@ new_undo_stack(Diagram *dia)
   return stack;
 }
 
+
 void
 undo_destroy(UndoStack *stack)
 {
   undo_clear(stack);
 
-  g_free(stack);
+  g_free (stack);
 }
 
+
 static void
 undo_remove_redo_info(UndoStack *stack)
 {
@@ -425,9 +427,9 @@ dia_move_objects_change_free (DiaChange *self)
 {
   DiaMoveObjectsChange *change = DIA_MOVE_OBJECTS_CHANGE (self);
 
-  g_free(change->orig_pos);
-  g_free(change->dest_pos);
-  g_list_free(change->obj_list);
+  g_clear_pointer (&change->orig_pos, g_free);
+  g_clear_pointer (&change->dest_pos, g_free);
+  g_list_free (change->obj_list);
 }
 
 
@@ -986,9 +988,11 @@ dia_object_change_change_free (DiaChange *self)
   DiaObjectChangeChange *change = DIA_OBJECT_CHANGE_CHANGE (self);
 
   g_debug ("state_change_free()");
-  if (change->obj_change->free)
-    (*change->obj_change->free)(change->obj_change);
-  g_free(change->obj_change);
+  if (change->obj_change->free) {
+    (*change->obj_change->free) (change->obj_change);
+  }
+
+  g_clear_pointer (&change->obj_change, g_free);
 }
 
 
@@ -1728,7 +1732,7 @@ dia_add_guide_change_apply (DiaChange *self, Diagram *dia)
   g_debug ("add_guide_apply()");
 
   new_guide = dia_diagram_add_guide (dia, change->guide->position, change->guide->orientation, FALSE);
-  g_free (change->guide);
+  g_clear_pointer (&change->guide, g_free);
   change->guide = new_guide;
 
   /* Force redraw. */
@@ -1768,7 +1772,7 @@ dia_add_guide_change_free (DiaChange *self)
   g_debug ("add_guide_free()");
 
   if (!change->applied) {
-    g_free (change->guide);
+    g_clear_pointer (&change->guide, g_free);
   }
 }
 
@@ -1835,7 +1839,7 @@ dia_delete_guide_change_revert (DiaChange *self, Diagram *dia)
                                      FALSE);
 
   /* Reassign. */
-  g_free (change->guide);
+  g_clear_pointer (&change->guide, g_free);
   change->guide = new_guide;
 
   /* Force redraw. */
@@ -1856,7 +1860,7 @@ dia_delete_guide_change_free (DiaChange *self)
   g_debug ("delete_guide_free()");
 
   if (change->applied) {
-    g_free (change->guide);
+    g_clear_pointer (&change->guide, g_free);
   }
 }
 
diff --git a/app/winmain.c b/app/winmain.c
index b8a7b3bc..059f388e 100644
--- a/app/winmain.c
+++ b/app/winmain.c
@@ -5,7 +5,7 @@
 #include <gtk/gtk.h> /* just for version */
 
 #ifdef G_OS_WIN32
-#define Rectangle Win32Rectangle 
+#define Rectangle Win32Rectangle
 #define WIN32_LEAN_AND_MEAN
 #include <windows.h> /* native file api */
 #undef Rectangle
@@ -43,7 +43,7 @@ WinMain (struct HINSTANCE__ *hInstance,
     setProcessDPIAware ();
 
   dia_redirect_console ();
-  
+
   app_init (__argc, __argv);
 
   if (!app_is_interactive())
@@ -52,7 +52,7 @@ WinMain (struct HINSTANCE__ *hInstance,
   toolbox_show();
 
   app_splash_done();
-  
+
   gtk_main ();
 
   return 0;
@@ -100,7 +100,7 @@ dia_log_func (const gchar    *log_domain,
 void
 dia_print_func (const char* string)
 {
-  
+
 }
 
 void
@@ -131,13 +131,13 @@ dia_redirect_console (void)
     /* overwrite at startup */
     redirected = g_build_filename (g_get_tmp_dir (), logname, NULL);
     /* not using standard c runtime functions to
-     * deal with possibly multiple instances 
-     */    
+     * deal with possibly multiple instances
+     */
     file = CreateFile (redirected, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 
FILE_FLAG_WRITE_THROUGH, 0);
     if (file == INVALID_HANDLE_VALUE)
       {
         i++;
-        g_free (redirected);
+        g_clear_pointer (&redirected, g_free);
         logname[3] = '0' + i;
       }
   } while (file == INVALID_HANDLE_VALUE && i < MAX_TRIES);
@@ -164,9 +164,9 @@ dia_redirect_console (void)
         {
           char* emsg = g_win32_error_message (GetLastError ());
           g_printerr ("Logfile %s writing failed: %s", redirected, emsg);
-          g_free (emsg);
+          g_clear_pointer (&emsg, g_free);
         }
-      g_free (log);
+      g_clear_pointer (&log, g_free);
     }
 }
 
diff --git a/lib/arrows.c b/lib/arrows.c
index 53bf3599..6395ebdf 100644
--- a/lib/arrows.c
+++ b/lib/arrows.c
@@ -108,7 +108,7 @@ dia_arrow_copy (Arrow *self)
 void
 dia_arrow_free (Arrow *self)
 {
-  g_free (self);
+  g_clear_pointer (&self, g_free);
 }
 
 
diff --git a/lib/autoroute.c b/lib/autoroute.c
index c6cbdfcf..3585f7c4 100644
--- a/lib/autoroute.c
+++ b/lib/autoroute.c
@@ -177,7 +177,7 @@ autoroute_layout_orthconn(OrthConn *conn,
                   this_badness, min_badness);
            */
            min_badness = this_badness;
-           if (best_layout != NULL) g_free(best_layout);
+           g_clear_pointer (&best_layout, g_free);
            best_layout = unnormalized;
            best_num_points = this_num_points;
             /* revert adjusting start and end point */
@@ -187,7 +187,7 @@ autoroute_layout_orthconn(OrthConn *conn,
                                        -conn->extra_spacing.end_trans);
            best_intersects = intersects;
          } else {
-           g_free(unnormalized);
+           g_clear_pointer (&unnormalized, g_free);
          }
        }
       }
@@ -196,10 +196,10 @@ autoroute_layout_orthconn(OrthConn *conn,
 
   if (min_badness < MAX_BADNESS) {
     orthconn_set_points(conn, best_num_points, best_layout);
-    g_free(best_layout);
+    g_clear_pointer (&best_layout, g_free);
     return TRUE;
   } else {
-    g_free(best_layout);
+    g_clear_pointer (&best_layout, g_free);
     return FALSE;
   }
 }
@@ -679,6 +679,6 @@ autolayout_unnormalize_points(guint startdir,
       point_add(&newpoints[i], &start);
     }
   }
-  g_free(points);
+  g_clear_pointer (&points, g_free);
   return newpoints;
 }
diff --git a/lib/bezier_conn.c b/lib/bezier_conn.c
index e66637ba..fd8e35e9 100644
--- a/lib/bezier_conn.c
+++ b/lib/bezier_conn.c
@@ -747,9 +747,10 @@ bezierconn_update_data (BezierConn *bezier)
       object_unconnect (&bezier->object, bezier->object.handles[obj->num_handles-1]);
 
     /* delete the old ones */
-    for (i = 0; i < obj->num_handles; i++)
-      g_free(obj->handles[i]);
-    g_free(obj->handles);
+    for (i = 0; i < obj->num_handles; i++) {
+      g_clear_pointer (&obj->handles[i], g_free);
+    }
+    g_clear_pointer (&obj->handles, g_free);
 
     obj->num_handles = 3*bezier->bezier.num_points-2;
     obj->handles = g_new(Handle*, obj->num_handles);
@@ -904,12 +905,13 @@ bezierconn_destroy (BezierConn *bezier)
 
   object_destroy(&bezier->object);
 
-  for (i = 0; i < nh; i++)
-    g_free(temp_handles[i]);
-  g_free(temp_handles);
+  for (i = 0; i < nh; i++) {
+    g_clear_pointer (&temp_handles[i], g_free);
+  }
+  g_clear_pointer (&temp_handles, g_free);
 
-  g_free(bezier->bezier.points);
-  g_free(bezier->bezier.corner_types);
+  g_clear_pointer (&bezier->bezier.points, g_free);
+  g_clear_pointer (&bezier->bezier.corner_types, g_free);
 }
 
 
@@ -1037,12 +1039,9 @@ bezierconn_point_change_free (struct PointChange *change)
 {
   if ( (change->type==TYPE_ADD_POINT && !change->applied) ||
        (change->type==TYPE_REMOVE_POINT && change->applied) ){
-    g_free(change->handle1);
-    g_free(change->handle2);
-    g_free(change->handle3);
-    change->handle1 = NULL;
-    change->handle2 = NULL;
-    change->handle3 = NULL;
+    g_clear_pointer (&change->handle1, g_free);
+    g_clear_pointer (&change->handle2, g_free);
+    g_clear_pointer (&change->handle3, g_free);
   }
 }
 
diff --git a/lib/beziershape.c b/lib/beziershape.c
index b0859ed6..066ef5b2 100644
--- a/lib/beziershape.c
+++ b/lib/beziershape.c
@@ -737,11 +737,11 @@ beziershape_update_data (BezierShape *bezier)
 
     /* delete the old ones */
     for (i = 0; i < obj->num_handles; i++)
-      g_free(obj->handles[i]);
-    g_free(obj->handles);
+      g_clear_pointer (&obj->handles[i], g_free);
+    g_clear_pointer (&obj->handles, g_free);
     for (i = 0; i < obj->num_connections; i++)
-      g_free(obj->connections[i]);
-    g_free(obj->connections);
+      g_clear_pointer (&obj->connections[i], g_free);
+    g_clear_pointer (&obj->connections, g_free);
 
     obj->num_handles = 3*(bezier->bezier.num_points-1);
     obj->handles = g_new(Handle*, obj->num_handles);
@@ -961,17 +961,17 @@ beziershape_destroy (BezierShape *bezier)
   object_destroy (&bezier->object);
 
   for (i = 0; i < nh; i++) {
-    g_free (temp_handles[i]);
+    g_clear_pointer (&temp_handles[i], g_free);
   }
-  g_free (temp_handles);
+  g_clear_pointer (&temp_handles, g_free);
 
   for (i = 0; i < bezier->object.num_connections; i++) {
-    g_free (temp_cps[i]);
+    g_clear_pointer (&temp_cps[i], g_free);
   }
-  g_free (temp_cps);
+  g_clear_pointer (&temp_cps, g_free);
 
-  g_free (bezier->bezier.points);
-  g_free (bezier->bezier.corner_types);
+  g_clear_pointer (&bezier->bezier.points, g_free);
+  g_clear_pointer (&bezier->bezier.corner_types, g_free);
 }
 
 
@@ -1100,16 +1100,11 @@ beziershape_point_change_free (struct BezPointChange *change)
 {
   if ( (change->type==TYPE_ADD_POINT && !change->applied) ||
        (change->type==TYPE_REMOVE_POINT && change->applied) ){
-    g_free(change->handle1);
-    g_free(change->handle2);
-    g_free(change->handle3);
-    g_free(change->cp1);
-    g_free(change->cp2);
-    change->handle1 = NULL;
-    change->handle2 = NULL;
-    change->handle3 = NULL;
-    change->cp1 = NULL;
-    change->cp2 = NULL;
+    g_clear_pointer (&change->handle1, g_free);
+    g_clear_pointer (&change->handle2, g_free);
+    g_clear_pointer (&change->handle3, g_free);
+    g_clear_pointer (&change->cp1, g_free);
+    g_clear_pointer (&change->cp2, g_free);
   }
 }
 
diff --git a/lib/boundingbox.c b/lib/boundingbox.c
index bc8582b4..ab10e478 100644
--- a/lib/boundingbox.c
+++ b/lib/boundingbox.c
@@ -241,6 +241,7 @@ ellipse_bbox(const Point *centre, real width, real height,
   rectangle_bbox(&rin,extra,rect);
 }
 
+
 /**  Allocate some scratch space to hold a big enough Bezier.
  * That space is not guaranteed to be preserved upon the next allocation
  * (in fact it's guaranteed it's not).
@@ -248,19 +249,21 @@ ellipse_bbox(const Point *centre, real width, real height,
  * @returns Newly allocated array of points.
  */
 static BezPoint *
-alloc_polybezier_space(int numpoints)
+alloc_polybezier_space (int numpoints)
 {
   static int alloc_np = 0;
   static BezPoint *alloced = NULL;
 
   if (alloc_np < numpoints) {
-    g_free(alloced);
+    g_clear_pointer (&alloced, g_free);
     alloc_np = numpoints;
-    alloced = g_new0(BezPoint,numpoints);
+    alloced = g_new0 (BezPoint, numpoints);
   }
+
   return alloced;
 }
 
+
 /** Free the scratch space allocated above.
  * @param points Previously allocated list of points.
  * @note Doesn't actually free it, as alloc_polybezier_space does that.
diff --git a/lib/color.c b/lib/color.c
index 446912b8..af56978b 100644
--- a/lib/color.c
+++ b/lib/color.c
@@ -95,7 +95,7 @@ dia_colour_copy (Color *self)
 void
 dia_colour_free (Color *self)
 {
-  g_free (self);
+  g_clear_pointer (&self, g_free);
 }
 
 
diff --git a/lib/connpoint_line.c b/lib/connpoint_line.c
index 1d98d5fe..0b40abdc 100644
--- a/lib/connpoint_line.c
+++ b/lib/connpoint_line.c
@@ -1,5 +1,5 @@
-/* 
- * SADT diagram support for dia 
+/*
+ * SADT diagram support for dia
  * Copyright(C) 2000 Cyrille Chepelov
  *
  * This program is free software; you can redistribute it and/or modify
@@ -29,20 +29,25 @@
 
 static void cpl_reorder_connections(ConnPointLine *cpl);
 
-inline static ConnectionPoint *new_connpoint(DiaObject *obj)
+
+inline static ConnectionPoint *
+new_connpoint (DiaObject *obj)
 {
-  ConnectionPoint *cp = g_new0(ConnectionPoint,1);
+  ConnectionPoint *cp = g_new0 (ConnectionPoint,1);
   cp->object = obj;
   return cp;
 }
 
-inline static void del_connpoint(ConnectionPoint *cp)
+
+inline static void
+del_connpoint (ConnectionPoint *cp)
 {
-  g_free(cp);
+  g_clear_pointer (&cp, g_free);
 }
 
+
 static ConnectionPoint *
-cpl_remove_connpoint(ConnPointLine *cpl,int pos) 
+cpl_remove_connpoint(ConnPointLine *cpl,int pos)
 {
   ConnectionPoint *cp;
 
@@ -59,7 +64,7 @@ cpl_remove_connpoint(ConnPointLine *cpl,int pos)
 
   cpl->connections = g_slist_remove(cpl->connections,(gpointer)cp);
   object_remove_connectionpoint(cpl->parent,cp);
-  
+
   cpl->num_connections--;
   /* removing a point doesn't change the order of the remaining ones, so we
      don't need to call cpl_reorder_connections. */
@@ -68,10 +73,10 @@ cpl_remove_connpoint(ConnPointLine *cpl,int pos)
 }
 
 static void
-cpl_add_connectionpoint_at(ConnPointLine *cpl, int pos,ConnectionPoint *cp) 
+cpl_add_connectionpoint_at(ConnPointLine *cpl, int pos,ConnectionPoint *cp)
 {
   if (pos == 0) {
-    /* special case handling so that the order of CPL groups in 
+    /* special case handling so that the order of CPL groups in
        the parent's CP list is preserved. */
     int fpos,i;
     ConnectionPoint *fcp;
@@ -106,21 +111,21 @@ cpl_add_connectionpoint_at(ConnPointLine *cpl, int pos,ConnectionPoint *cp)
      several CP's are added at once (initialisation). */
 }
 
-inline static void 
+inline static void
 cpl_add_connectionpoint(ConnPointLine *cpl,ConnectionPoint *cp)
 {
   cpl_add_connectionpoint_at(cpl,-1,cp);
 }
 
 ConnPointLine *
-connpointline_create(DiaObject *parent, int num_connections) 
+connpointline_create(DiaObject *parent, int num_connections)
 {
   ConnPointLine *cpl;
   int i;
 
   cpl = g_new0(ConnPointLine,1);
   cpl->parent = parent;
-  
+
   cpl->connections = NULL;
   for (i=0; i<num_connections; i++) {
     cpl_add_connectionpoint(cpl,new_connpoint(cpl->parent));
@@ -129,13 +134,18 @@ connpointline_create(DiaObject *parent, int num_connections)
   return cpl;
 }
 
-void 
-connpointline_destroy(ConnPointLine *cpl)
+
+void
+connpointline_destroy (ConnPointLine *cpl)
 {
-  while (cpl->num_connections > 0) del_connpoint(cpl_remove_connpoint(cpl,0));
-  g_free(cpl);
+  while (cpl->num_connections > 0) {
+    del_connpoint (cpl_remove_connpoint (cpl, 0));
+  }
+
+  g_clear_pointer (&cpl, g_free);
 }
 
+
 static ConnPointLine *
 cpl_inplacecreate(DiaObject *obj, int nc, int *realconncount)
 {
@@ -147,7 +157,7 @@ cpl_inplacecreate(DiaObject *obj, int nc, int *realconncount)
      connection points to the parent object. */
   newcpl = g_new0(ConnPointLine,1);
   newcpl->parent = obj;
-  
+
   for (i=0; i < nc; i++,(*realconncount)++) {
     cp = g_new0(ConnectionPoint,1);
     cp->object = newcpl->parent;
@@ -174,14 +184,14 @@ connpointline_load(DiaObject *obj,ObjectNode obj_node,
 
   if (realconncount) (*realconncount) += cpl->num_connections;
   return cpl;
-  /* NOT this ! 
+  /* NOT this !
   return cpl_inplacecreate(obj,
                           load_int(obj_node,name,default_nc),
                           realconncount);
   */
 }
 
-void 
+void
 connpointline_save(ConnPointLine *cpl,ObjectNode obj_node,
                   const gchar *name, DiaContext *ctx)
 {
@@ -200,7 +210,7 @@ void connpointline_update(ConnPointLine *cpl)
 
 }
 
-void 
+void
 connpointline_putonaline(ConnPointLine *cpl,Point *start,Point *end, gint dirs)
 {
   Point se_vector;
@@ -210,15 +220,15 @@ connpointline_putonaline(ConnPointLine *cpl,Point *start,Point *end, gint dirs)
 
   point_copy(&se_vector, end);
   point_sub(&se_vector, start);
-  
+
   se_len = point_len(&se_vector);
-  
+
   if (se_len > 0)
     point_normalize(&se_vector);
-  
+
   cpl->start = *start;
   cpl->end = *end;
-  
+
   if (dirs != DIR_NONE)
     /* use the oone givne by the caller */;
   else if (fabs(se_vector.x) > fabs(se_vector.y))
@@ -226,10 +236,10 @@ connpointline_putonaline(ConnPointLine *cpl,Point *start,Point *end, gint dirs)
   else
     dirs = DIR_EAST|DIR_WEST;
 
-  pseudopoints = cpl->num_connections + 1; /* here, we count the start and end 
+  pseudopoints = cpl->num_connections + 1; /* here, we count the start and end
                                            points as eating real positions. */
-  for (i=0, elem=cpl->connections; 
-       i<cpl->num_connections; 
+  for (i=0, elem=cpl->connections;
+       i<cpl->num_connections;
        i++,elem=g_slist_next(elem)) {
     ConnectionPoint *cp = (ConnectionPoint *)(elem->data);
     cp->pos = se_vector;
@@ -242,7 +252,7 @@ connpointline_putonaline(ConnPointLine *cpl,Point *start,Point *end, gint dirs)
 
 /* These object_* functions are useful to me, because of what they do, I think
    they belong to lib/object.c ; should I move them ? */
-static void 
+static void
 object_move_connection(DiaObject *obj,int sourcepos,int destpos)
 {
   ConnectionPoint *cp;
@@ -283,8 +293,8 @@ static void cpl_dump_connections(ConnPointLine *cpl)
   ConnectionPoint *cp;
 
   g_message("CPL order dump");
-  for (i=0,elem = cpl->connections; 
-       i<cpl->num_connections; 
+  for (i=0,elem = cpl->connections;
+       i<cpl->num_connections;
        i++,elem = g_slist_next(elem)) {
     cp = (ConnectionPoint *)(elem->data);
     g_message("connection %p %d@CPL %d@OBJ",
@@ -293,18 +303,18 @@ static void cpl_dump_connections(ConnPointLine *cpl)
 }
 #endif
 
-static void 
+static void
 cpl_reorder_connections(ConnPointLine *cpl)
 {
   /* This is needed, so that we don't mess up the loaded connections if
      we save after the user has removed and added some connection points.
-     Normally, if an object owns several CPL, the order of the groups of 
+     Normally, if an object owns several CPL, the order of the groups of
      connectionpoints in its connectionpoint list should not change, as long
-     as we call this function whenever we do something. 
-  
-     The CPL has two big responsiblities here : first, it messes with 
-     the parent object's structures (ugh), second, it must ensure that its 
-     first CP is inserted so that it is found first in the parent's CP list, 
+     as we call this function whenever we do something.
+
+     The CPL has two big responsiblities here : first, it messes with
+     the parent object's structures (ugh), second, it must ensure that its
+     first CP is inserted so that it is found first in the parent's CP list,
      and that the order of CP groups in the parent's CP list is respected (so
      that the parent could have several different CPL and rely on the order).
   */
@@ -330,11 +340,11 @@ cpl_reorder_connections(ConnPointLine *cpl)
     }
   }
   g_assert(first >= 0); /* otherwise things went loose badly. */
-  for (i=0,j=first,elem=cpl->connections; 
-       i<cpl->num_connections; 
+  for (i=0,j=first,elem=cpl->connections;
+       i<cpl->num_connections;
        elem=g_slist_next(elem),i++,j++) {
     cp = (ConnectionPoint *)(elem->data); /* = cpl->connections[i] */
-    if ( cp != obj->connections[j]) { /* first time will always be false. 
+    if ( cp != obj->connections[j]) { /* first time will always be false.
                                         Is GCC that smart ? Probably not. */
       object_move_connection(obj,object_find_connection(obj,cp,j),j);
     }
@@ -345,16 +355,15 @@ cpl_reorder_connections(ConnPointLine *cpl)
 #endif
 #if DEBUG_PARENT
   j = 0;
-  for (i=0; i<cpl->parent->num_connections;i++) 
+  for (i=0; i<cpl->parent->num_connections;i++)
     if (!cpl->parent->connections[i]) j++;
   /* We should never make such holes !*/
   if (j) g_warning("in cpl_reorder_connections there are %d holes in the parent's ConnectionPoint list !",j);
 #endif
 }
-  
-  
 
-int 
+
+int
 connpointline_can_add_point(ConnPointLine *cpl, Point *clicked)
 {
   return 1;
@@ -369,8 +378,8 @@ connpointline_can_remove_point(ConnPointLine *cpl, Point *clicked)
     return 1;
 }
 
-static int 
-cpl_get_pointbefore(ConnPointLine *cpl, Point *clickedpoint) 
+static int
+cpl_get_pointbefore(ConnPointLine *cpl, Point *clickedpoint)
 {
   int i, pos = -1;
   GSList *elem;
@@ -381,7 +390,7 @@ cpl_get_pointbefore(ConnPointLine *cpl, Point *clickedpoint)
   if (!clickedpoint) return 0;
 
   for (i=0,elem=cpl->connections;
-       i<cpl->num_connections; 
+       i<cpl->num_connections;
        i++,elem=g_slist_next(elem)) {
     cp = (ConnectionPoint *)(elem->data);
 
@@ -398,10 +407,10 @@ cpl_get_pointbefore(ConnPointLine *cpl, Point *clickedpoint)
   }
   return pos;
 }
- 
+
 typedef struct {
   ObjectChange obj_change;
-  
+
   int add; /* How much to add or remove */
   int applied; /* 1 if the event has been applied. */
 
@@ -410,7 +419,7 @@ typedef struct {
   ConnectionPoint **cp; /* The removed connection point. */
 } CPLChange;
 
-static void 
+static void
 cpl_change_addremove(CPLChange *change, ConnPointLine *cpl,
                     int action, int resultingapplied)
 {
@@ -429,22 +438,24 @@ cpl_change_addremove(CPLChange *change, ConnPointLine *cpl,
   } else {
     g_warning("cpl_change_addremove(): null action !");
   }
-  change->applied = resultingapplied; 
+  change->applied = resultingapplied;
 }
 
-static void 
-cpl_change_apply(CPLChange *change, ConnPointLine *probablynotcpl) 
+static void
+cpl_change_apply(CPLChange *change, ConnPointLine *probablynotcpl)
 {
   cpl_change_addremove(change,change->cpl,change->add,1);
 }
 
-static void 
-cpl_change_revert(CPLChange *change, ConnPointLine *probablynotcpl) 
+static void
+cpl_change_revert(CPLChange *change, ConnPointLine *probablynotcpl)
 {
   cpl_change_addremove(change,change->cpl,-(change->add),0);
 }
 
-static void cpl_change_free(CPLChange *change)
+
+static void
+cpl_change_free (CPLChange *change)
 {
   int i = ABS(change->add);
 
@@ -453,16 +464,19 @@ static void cpl_change_free(CPLChange *change)
       del_connpoint(change->cp[i]);
     }
   }
-  g_free(change->cp); change->cp = (ConnectionPoint **)(0xDEADBEEF);
+  g_clear_pointer (&change->cp, g_free);
+
+  change->cp = (ConnectionPoint **)(0xDEADBEEF);
 }
 
+
 static ObjectChange *
-cpl_create_change(ConnPointLine *cpl, int pos, int add) 
+cpl_create_change(ConnPointLine *cpl, int pos, int add)
 {
   CPLChange *change;
 
   change = g_new0(CPLChange,1);
-  
+
   change->obj_change.apply = (ObjectChangeApplyFunc) cpl_change_apply;
   change->obj_change.revert = (ObjectChangeRevertFunc) cpl_change_revert;
   change->obj_change.free = (ObjectChangeFreeFunc) cpl_change_free;
@@ -476,12 +490,12 @@ cpl_create_change(ConnPointLine *cpl, int pos, int add)
   while (add-- > 0) {
     change->cp[add] = new_connpoint(cpl->parent);
   }
-  
+
   return (ObjectChange *)change;
 }
 
 ObjectChange *
-connpointline_add_points(ConnPointLine *cpl, 
+connpointline_add_points(ConnPointLine *cpl,
                          Point *clickedpoint, int count)
 {
   int pos;
@@ -496,7 +510,7 @@ connpointline_add_points(ConnPointLine *cpl,
 
 
 ObjectChange *
-connpointline_remove_points(ConnPointLine *cpl, 
+connpointline_remove_points(ConnPointLine *cpl,
                             Point *clickedpoint, int count)
 {
   int pos;
@@ -509,9 +523,11 @@ connpointline_remove_points(ConnPointLine *cpl,
   return change;
 }
 
-int 
-connpointline_adjust_count(ConnPointLine *cpl,
-                          int newcount, Point *where)
+
+int
+connpointline_adjust_count (ConnPointLine *cpl,
+                            int            newcount,
+                            Point         *where)
 {
   int oldcount,delta;
 
@@ -523,17 +539,17 @@ connpointline_adjust_count(ConnPointLine *cpl,
   if (delta != 0) {
     ObjectChange *change;
     /*g_message("going to adjust %d (to be %d)",delta,shouldbe);*/
-   
+
     if (delta > 0) {
-      change = connpointline_add_points(cpl, where, delta);
-    } else { 
-      change = connpointline_remove_points(cpl, where, -delta);
+      change = connpointline_add_points (cpl, where, delta);
+    } else {
+      change = connpointline_remove_points (cpl, where, -delta);
     }
-    if (change->free) change->free(change);
-    g_free(change); /* we don't really need this change object. */
-  }    
 
+    if (change->free) change->free (change);
+    g_clear_pointer (&change, g_free);
+    /* we don't really need this change object. */
+  }
 
   return oldcount;
 }
-
diff --git a/lib/create.c b/lib/create.c
index 35b9a48a..9b96838b 100644
--- a/lib/create.c
+++ b/lib/create.c
@@ -410,7 +410,7 @@ create_standard_image(real xpos, real ypos, real width, real height,
     props = prop_list_from_descs (create_file_prop_descs, pdtpp_true);
     g_assert (props->len == 1);
     sprop = g_ptr_array_index (props, 0);
-    g_free (sprop->string_data);
+    g_clear_pointer (&sprop->string_data, g_free);
     sprop->string_data = g_strdup (file);
     dia_object_set_properties (new_obj, props);
     prop_list_free (props);
diff --git a/lib/dia-guide.c b/lib/dia-guide.c
index 99160129..5f0731d9 100644
--- a/lib/dia-guide.c
+++ b/lib/dia-guide.c
@@ -41,7 +41,7 @@ dia_guide_copy (DiaGuide * self)
 void
 dia_guide_free (DiaGuide * self)
 {
-  g_free (self);
+  g_clear_pointer (&self, g_free);
 }
 
 
diff --git a/lib/dia_dirs.c b/lib/dia_dirs.c
index 5f0da34c..5cea050d 100644
--- a/lib/dia_dirs.c
+++ b/lib/dia_dirs.c
@@ -96,17 +96,17 @@ dia_get_data_directory(const gchar* subdir)
     returnPath = g_strdup(tmpPath);
   else
     returnPath = g_build_path(G_DIR_SEPARATOR_S, tmpPath, subdir, NULL);
-  g_free(tmpPath);
+  g_clear_pointer (&tmpPath, g_free);
 #  else
   returnPath = g_strconcat (sLoc , subdir, NULL);
 #  endif
-  g_free (sLoc);
+  g_clear_pointer (&sLoc, g_free);
   return returnPath;
 #else
   gchar *base = g_strdup (PKGDATADIR);
   char  *ret;
   if (g_getenv ("DIA_BASE_PATH") != NULL) {
-    g_free (base);
+    g_clear_pointer (&base, g_free);
     /* a small hack cause the final destination and the local path differ */
     base = g_build_filename (g_getenv ("DIA_BASE_PATH"), "data", NULL);
   }
@@ -114,7 +114,7 @@ dia_get_data_directory(const gchar* subdir)
     ret = g_strconcat (base, NULL);
   else
     ret = g_strconcat (base, G_DIR_SEPARATOR_S, subdir, NULL);
-  g_free (base);
+  g_clear_pointer (&base, g_free);
   return ret;
 #endif
 }
@@ -136,7 +136,7 @@ dia_get_lib_directory(void)
 #  else
   returnPath = g_strconcat (sLoc , "dia", NULL);
 #  endif
-  g_free (sLoc);
+  g_clear_pointer (&sLoc, g_free);
   return returnPath;
 #else
   return g_strconcat (DIALIBDIR, G_DIR_SEPARATOR_S, "", NULL);
@@ -201,7 +201,7 @@ dia_config_ensure_dir(const gchar *filename)
   } else {
     exists = FALSE;
   }
-  g_free(dir);
+  g_clear_pointer (&dir, g_free);
   return exists;
 }
 
@@ -225,18 +225,18 @@ dia_get_canonical_path(const gchar *path)
   while (list[i] != NULL) {
     if (0 == strcmp (list[i], ".")) {
       /* simple, just remove it */
-      g_free (list[i]);
+      g_clear_pointer (&list[i], g_free);
       list[i] = g_strdup ("");
     }
     else if  (0 == strcmp (list[i], "..")) {
       /* need to 'remove' the previous non empty part too */
       n = i;
-      g_free (list[i]);
+      g_clear_pointer (&list[i], g_free);
       list[i] = g_strdup ("");
       while (n >= 0) {
         if (0 != strlen(list[n])) {
           /* remove it */
-          g_free (list[n]);
+          g_clear_pointer (&list[n], g_free);
           list[n] = g_strdup ("");
           break;
         }
@@ -290,7 +290,7 @@ dia_message_filename(const gchar *filename)
   /* Stick in the quark table so that we can return a static result
    */
   msg_quark = g_quark_from_string (tmp);
-  g_free (tmp);
+  g_clear_pointer (&tmp, g_free);
   tmp = (gchar *) g_quark_to_string (msg_quark);
   return tmp;
 }
@@ -309,7 +309,7 @@ dia_get_absolute_filename (const gchar *filename)
   if (g_path_is_absolute(filename)) return dia_get_canonical_path(filename);
   current_dir = g_get_current_dir();
   fullname = g_build_filename(current_dir, filename, NULL);
-  g_free(current_dir);
+  g_clear_pointer (&current_dir, g_free);
   if (strchr(fullname, '.') == NULL) return fullname;
   canonical = dia_get_canonical_path(fullname);
   if (canonical == NULL) {
@@ -317,7 +317,7 @@ dia_get_absolute_filename (const gchar *filename)
                     dia_message_filename(filename));
     return g_strdup(filename);
   }
-  g_free(fullname);
+  g_clear_pointer (&fullname, g_free);
   return canonical;
 }
 
@@ -353,18 +353,20 @@ dia_relativize_filename (const gchar *master, const gchar *slave)
     for (p = rel; *p != '\0'; p++)
       if (*p == '\\') *p = '/';
   }
-  g_free (bp1);
-  g_free (bp2);
+  g_clear_pointer (&bp1, g_free);
+  g_clear_pointer (&bp2, g_free);
 
   return rel;
 }
 
-gchar *
-dia_absolutize_filename (const gchar *master, const gchar *slave)
+
+char *
+dia_absolutize_filename (const char *master, const char *slave)
 {
-  gchar *path = g_path_get_dirname (master);
-  gchar *result = g_build_path (G_DIR_SEPARATOR_S, path, slave, NULL);
+  char *path = g_path_get_dirname (master);
+  char *result = g_build_path (G_DIR_SEPARATOR_S, path, slave, NULL);
+
+  g_clear_pointer (&path, g_free);
 
-  g_free (path);
   return result;
 }
diff --git a/lib/dia_image.c b/lib/dia_image.c
index 1f769294..517f751b 100644
--- a/lib/dia_image.c
+++ b/lib/dia_image.c
@@ -48,45 +48,35 @@ struct _DiaImage {
   cairo_surface_t *surface;
 };
 
+
 G_DEFINE_TYPE (DiaImage, dia_image, G_TYPE_OBJECT)
 
-/*!
- * \brief Destructor
- * \memberof _DiaImage
- */
+
 static void
-dia_image_finalize (GObject* object)
+dia_image_finalize (GObject *object)
 {
-  DiaImage *image = DIA_IMAGE(object);
+  DiaImage *image = DIA_IMAGE (object);
 
-  if (image->scaled) {
-    g_object_unref (image->scaled);
-  }
-  image->scaled = NULL;
-
-  if (image->image) {
-    g_object_unref (image->image);
-  }
-  image->image = NULL;
+  g_clear_object (&image->scaled);
+  g_clear_object (&image->image);
 
-  g_free (image->filename);
-  image->filename = NULL;
-
-  g_free (image->mime_type);
-  image->mime_type = NULL;
+  g_clear_pointer (&image->filename, g_free);
+  g_clear_pointer (&image->mime_type, g_free);
 
   cairo_surface_destroy (image->surface);
   image->surface = NULL;
 }
 
+
 static void
-dia_image_class_init (DiaImageClass* klass)
+dia_image_class_init (DiaImageClass *klass)
 {
-  GObjectClass* object_class = G_OBJECT_CLASS (klass);
+  GObjectClass *object_class = G_OBJECT_CLASS (klass);
 
   object_class->finalize = dia_image_finalize;
 }
 
+
 /*!
  * \brief Constructor
  * \memberof _DiaImage
@@ -149,7 +139,9 @@ dia_image_load (const gchar *filename)
     if (g_file_test (filename, G_FILE_TEST_EXISTS)) {
       message_warning ("%s\n", error->message);
     }
-    g_error_free (error);
+
+    g_clear_error (&error);
+
     return NULL;
   }
 
@@ -205,6 +197,7 @@ dia_image_add_ref (DiaImage *image)
   g_object_ref (image);
 }
 
+
 /**
  * dia_image_unref:
  * @image: Image to unreference.
@@ -214,10 +207,11 @@ dia_image_add_ref (DiaImage *image)
 void
 dia_image_unref (DiaImage *image)
 {
-  // TODO: Drop
-  g_object_unref (image);
+  // TODO: Drop this func
+  g_clear_object (&image);
 }
 
+
 /*!
  * \brief Create a scaled variant of the underlying pixbuf.
  * @param image explicit this pointer
@@ -238,9 +232,7 @@ dia_image_get_scaled_pixbuf (DiaImage *image, int width, int height)
     /* Using TILES to make it look more like PostScript */
     if (image->scaled == NULL ||
         image->scaled_width != width || image->scaled_height != height) {
-      if (image->scaled) {
-        g_object_unref(image->scaled);
-      }
+      g_clear_object (&image->scaled);
       image->scaled = gdk_pixbuf_scale_simple (image->image,
                                                width,
                                                height,
@@ -316,7 +308,7 @@ dia_image_save (DiaImage *image, const gchar *filename)
       saved = gdk_pixbuf_save (image->image, filename, type, &error, NULL);
     }
     if (saved) {
-      g_free (image->filename);
+      g_clear_pointer (&image->filename, g_free);
       image->filename = g_strdup (filename);
     } else if (!type) {
       /* pathologic case - pixbuf not even supporting PNG? */
@@ -326,10 +318,10 @@ dia_image_save (DiaImage *image, const gchar *filename)
       message_warning (_("Could not save file:\n%s\n%s\n"),
                        dia_message_filename(filename),
                        error->message);
-      g_error_free (error);
+      g_clear_error (&error);
     }
 
-    g_free (type);
+    g_clear_pointer (&type, g_free);
   }
   return saved;
 }
@@ -417,7 +409,7 @@ dia_image_get_mime_type (const DiaImage *image)
 void
 dia_image_set_mime_type (DiaImage *image, const gchar *mime_type)
 {
-  g_free (image->mime_type);
+  g_clear_pointer (&image->mime_type, g_free);
 
   image->mime_type = g_strdup (mime_type);
 }
diff --git a/lib/dia_svg.c b/lib/dia_svg.c
index ea90652a..6f34ba72 100644
--- a/lib/dia_svg.c
+++ b/lib/dia_svg.c
@@ -373,9 +373,9 @@ _parse_color(gint32 *color, const char *str)
     } else {
       /* need to make a copy of the color only */
       gboolean ret;
-      gchar *sc = g_strndup (str, se - str);
+      char *sc = g_strndup (str, se - str);
       ret = svg_named_color (sc, color);
-      g_free (sc);
+      g_clear_pointer (&sc, g_free);
       return ret;
     }
   }
@@ -505,43 +505,50 @@ _parse_linecap (DiaSvgStyle *s, const char *val)
 static void
 _style_adjust_font (DiaSvgStyle *s, const char *family, const char *style, const char *weight)
 {
-    g_clear_object (&s->font);
-    /* given font_height is bogus, especially if not given at all
-     * or without unit ... see bug 665648 about invalid CSS
-     */
-    s->font = dia_font_new_from_style(DIA_FONT_SANS, s->font_height > 0 ? s->font_height : 1.0);
-    if (family) {
-      /* SVG allows a list of families here, also there is some strange formatting
-       * seen, like 'Arial'. If the given family name can not be resolved by
-       * Pango it complaints loudly with g_warning().
-       */
-      gchar **families = g_strsplit(family, ",", -1);
-      int i = 0;
-      gboolean found = FALSE;
-      while (!found && families[i]) {
-       const gchar *chomped = g_strchomp (g_strdelimit(families[i], "'", ' '));
-       PangoFont *loaded;
-        dia_font_set_any_family(s->font, chomped);
-       loaded = pango_context_load_font(dia_font_get_context(),
-                                        dia_font_get_description(s->font));
-       if (loaded) {
-         g_object_unref(loaded);
-         found = TRUE;
-       }
-       ++i;
+  g_clear_object (&s->font);
+  /* given font_height is bogus, especially if not given at all
+    * or without unit ... see bug 665648 about invalid CSS
+    */
+  s->font = dia_font_new_from_style (DIA_FONT_SANS, s->font_height > 0 ? s->font_height : 1.0);
+  if (family) {
+    /* SVG allows a list of families here, also there is some strange formatting
+      * seen, like 'Arial'. If the given family name can not be resolved by
+      * Pango it complaints loudly with g_warning().
+      */
+    gchar **families = g_strsplit (family, ",", -1);
+    int i = 0;
+    gboolean found = FALSE;
+    while (!found && families[i]) {
+      const char *chomped = g_strchomp (g_strdelimit (families[i], "'", ' '));
+      PangoFont *loaded;
+
+      dia_font_set_any_family(s->font, chomped);
+      loaded = pango_context_load_font (dia_font_get_context (),
+                                        dia_font_get_description (s->font));
+      if (loaded) {
+        g_clear_object (&loaded);
+        found = TRUE;
       }
-      if (!found)
-       dia_font_set_any_family(s->font, "sans");
-      g_strfreev(families);
+      ++i;
     }
-    if (style) {
-      dia_font_set_slant_from_string(s->font,style);
-    }
-    if (weight) {
-      dia_font_set_weight_from_string(s->font,weight);
+
+    if (!found) {
+      dia_font_set_any_family (s->font, "sans");
     }
+
+    g_strfreev (families);
+  }
+
+  if (style) {
+    dia_font_set_slant_from_string (s->font, style);
+  }
+
+  if (weight) {
+    dia_font_set_weight_from_string (s->font, weight);
+  }
 }
 
+
 static void
 _parse_text_align(DiaSvgStyle *s, const gchar *ptr)
 {
@@ -723,9 +730,9 @@ dia_svg_parse_style_string (DiaSvgStyle *s, real user_scale, const gchar *str)
   if (family || style || weight) {
     _style_adjust_font (s, family, style, weight);
 
-    g_free(family);
-    g_free(style);
-    g_free(weight);
+    g_clear_pointer (&family, g_free);
+    g_clear_pointer (&style, g_free);
+    g_clear_pointer (&weight, g_free);
   }
 }
 
diff --git a/lib/dia_xml.c b/lib/dia_xml.c
index faaa68a2..b5efbeac 100644
--- a/lib/dia_xml.c
+++ b/lib/dia_xml.c
@@ -117,138 +117,167 @@ static inline int isinf_ld (long double x) { return isnan (x - x); }
  *       better than this. I dont. --hb
  * \ingroup DiagramXmlIo
  */
-static const gchar *
-xml_file_check_encoding(const gchar *filename, const gchar *default_enc, DiaContext *ctx)
+static char *
+xml_file_check_encoding (const char *filename,
+                         const char *default_enc,
+                         DiaContext *ctx)
 {
   int fd = g_open (filename, O_RDONLY, 0);
   /* If the next call exits the program (without any message) check if
    * you are loading an incompatible version of zlib*.dll, e.g. one
    * built against a newer version of msvcrt*.dll
    */
-  gzFile zf = gzdopen(fd,"rb");
-  gchar *buf;
-  gchar *p,*pmax;
+  gzFile zf = gzdopen (fd, "rb");
+  char *buf;
+  char *p,*pmax;
   int len;
-  gchar *tmp,*res;
   int uf;
   gboolean well_formed_utf8;
   int write_ok;
+  char *res = g_strdup (filename);
+  GError *error = NULL;
 
   static char magic_xml[] =
   {0x3c,0x3f,0x78,0x6d,0x6c,0x00}; /* "<?xml" in ASCII */
 
   if (!zf) {
-    dia_log_message("%s can not be opened for encoding check (%s)", filename, fd > 0 ? "gzdopen" : "g_open");
+    dia_log_message ("%s can not be opened for encoding check (%s)",
+                     filename,
+                     fd > 0 ? "gzdopen" : "g_open");
     /* XXX perhaps we can just chicken out to libxml ? -- CC */
-    return filename;
+    return res;
   }
-  p = buf = g_malloc0(BUFLEN);
-  len = gzread(zf,buf,BUFLEN);
+
+  p = buf = g_malloc0 (BUFLEN);
+  len = gzread (zf, buf, BUFLEN);
   pmax = p + len;
 
   /* first, we expect the magic <?xml string */
-  if ((0 != strncmp(p,magic_xml,5)) || (len < 5)) {
-    gzclose(zf);
-    g_free(buf);
-    return filename; /* let libxml figure out what this is. */
+  if ((0 != strncmp (p, magic_xml, 5)) || (len < 5)) {
+    gzclose (zf);
+    g_clear_pointer (&buf, g_free);
+    return res; /* let libxml figure out what this is. */
   }
+
   /* now, we're sure we have some asciish XML file. */
   p += 5;
-  while (((*p == 0x20)||(*p == 0x09)||(*p == 0x0d)||(*p == 0x0a))
-         && (p<pmax)) p++;
-  if (p>=pmax) { /* whoops ? */
-    gzclose(zf);
-    g_free(buf);
-    return filename;
+  while (((*p == 0x20) || (*p == 0x09) || (*p == 0x0d) || (*p == 0x0a))
+         && (p < pmax)) {
+    p++;
+  }
+
+  if (p >= pmax) { /* whoops ? */
+    gzclose (zf);
+    g_clear_pointer (&buf, g_free);
+    return res;
   }
-  if (0 != strncmp(p,"version=\"",9)) {
-    gzclose(zf); /* chicken out. */
-    g_free(buf);
-    return filename;
+
+  if (0 != strncmp (p, "version=\"", 9)) {
+    gzclose (zf); /* chicken out. */
+    g_clear_pointer (&buf, g_free);
+    return res;
   }
   p += 9;
+
   /* The header is rather well formed. */
   if (p>=pmax) { /* whoops ? */
     gzclose(zf);
-    g_free(buf);
-    return filename;
+    g_clear_pointer (&buf, g_free);
+    return res;
+  }
+
+  while ((*p != '"') && (p < pmax)) {
+    p++;
   }
-  while ((*p != '"') && (p < pmax)) p++;
   p++;
+
   while (((*p == 0x20)||(*p == 0x09)||(*p == 0x0d)||(*p == 0x0a))
-         && (p<pmax)) p++;
-  if (p>=pmax) { /* whoops ? */
-    gzclose(zf);
-    g_free(buf);
-    return filename;
+         && (p<pmax)) {
+    p++;
+  }
+
+  if (p >= pmax) { /* whoops ? */
+    gzclose (zf);
+    g_clear_pointer (&buf, g_free);
+    return res;
   }
-  if (0 == strncmp(p,"encoding=\"",10)) {
+
+  if (0 == strncmp (p, "encoding=\"", 10)) {
     gzclose(zf); /* this file has an encoding string. Good. */
-    g_free(buf);
-    return filename;
+    g_clear_pointer (&buf, g_free);
+    return res;
   }
+
   /* now let's read the whole file, to see if there are offending bits.
    * We can call it well formed UTF-8 if the highest isn't used
    */
   well_formed_utf8 = TRUE;
   do {
     int i;
-    for (i = 0; i < len; i++)
-      if (buf[i] & 0x80 || buf[i] == '&')
+    for (i = 0; i < len; i++) {
+      if (buf[i] & 0x80 || buf[i] == '&') {
         well_formed_utf8 = FALSE;
-    len = gzread(zf,buf,BUFLEN);
+      }
+    }
+    len = gzread (zf, buf, BUFLEN);
   } while (len > 0 && well_formed_utf8);
+
   if (well_formed_utf8) {
-    gzclose(zf); /* this file is utf-8 compatible  */
-    g_free(buf);
-    return filename;
+    gzclose (zf); /* this file is utf-8 compatible  */
+    g_clear_pointer (&buf, g_free);
+    return res;
   } else {
-    gzclose(zf); /* poor man's fseek */
+    gzclose (zf); /* poor man's fseek */
     fd = g_open (filename, O_RDONLY, 0);
-    zf = gzdopen(fd,"rb");
-    len = gzread(zf,buf,BUFLEN);
+    zf = gzdopen (fd,"rb");
+    len = gzread (zf, buf, BUFLEN);
   }
 
-  if (0 != strcmp(default_enc,"UTF-8")) {
+  if (0 != strcmp (default_enc, "UTF-8")) {
     dia_context_add_message (ctx,
                              _("The file %s has no encoding specification;\n"
-                            "assuming it is encoded in %s"),
-                            dia_context_get_filename(ctx), default_enc);
+                               "assuming it is encoded in %s"),
+                             dia_context_get_filename (ctx),
+                             default_enc);
   } else {
-    gzclose(zf); /* we apply the standard here. */
-    g_free(buf);
-    return filename;
+    gzclose (zf); /* we apply the standard here. */
+    g_clear_pointer (&buf, g_free);
+    return res;
   }
 
-  tmp = getenv("TMP");
-  if (!tmp) tmp = getenv("TEMP");
-  if (!tmp) tmp = "/tmp";
+  uf = g_file_open_tmp ("dia-xml-fix-encodingXXXXXX", &res, &error);
+
+  if (error) {
+    g_warning ("%s", error->message);
+  }
 
-  res = g_strconcat(tmp,G_DIR_SEPARATOR_S,"dia-xml-fix-encodingXXXXXX",NULL);
-  uf = g_mkstemp(res);
   write_ok = (uf > 0);
-  write_ok = write_ok && (write(uf,buf,p-buf) > 0);
-  write_ok = write_ok && (write(uf," encoding=\"",11) > 0);
-  write_ok = write_ok && (write(uf,default_enc,strlen(default_enc)) > 0);
-  write_ok = write_ok && (write(uf,"\" ",2) > 0);
-  write_ok = write_ok && (write(uf,p,pmax - p) > 0);
+  write_ok = write_ok && (write (uf, buf, p - buf) > 0);
+  write_ok = write_ok && (write (uf, " encoding=\"", 11) > 0);
+  write_ok = write_ok && (write (uf, default_enc, strlen (default_enc)) > 0);
+  write_ok = write_ok && (write (uf, "\" ", 2) > 0);
+  write_ok = write_ok && (write (uf, p, pmax - p) > 0);
 
   while (write_ok) {
-    len = gzread(zf,buf,BUFLEN);
-    if (len <= 0) break;
-    write_ok = write_ok && (write(uf,buf,len) > 0);
+    len = gzread (zf, buf, BUFLEN);
+    if (len <= 0) {
+      break;
+    }
+    write_ok = write_ok && (write (uf, buf, len) > 0);
   }
-  gzclose(zf);
-  if (uf > 0)
-    close(uf);
-  g_free(buf);
-  if (!write_ok) {
-    g_free(res);
-    res = NULL;
+
+  gzclose (zf);
+
+  if (uf > 0) {
+    close (uf);
   }
+
+  g_clear_pointer (&buf, g_free);
+
   return res; /* caller frees the name and unlinks the file. */
 }
 
+
 /*!
  * \brief Parse a given file into XML, handling old broken files correctly.
  * @param filename The name of the file to read.
@@ -258,32 +287,35 @@ xml_file_check_encoding(const gchar *filename, const gchar *default_enc, DiaCont
  * \ingroup DiagramXmlIo
  */
 static xmlDocPtr
-xmlDiaParseFile(const char *filename, DiaContext *ctx)
+xmlDiaParseFile (const char *filename, DiaContext *ctx)
 {
   const char *local_charset = NULL;
   xmlErrorPtr error_xml = NULL;
   xmlDocPtr ret = NULL;
 
-  if (   !g_get_charset(&local_charset)
+  if (   !g_get_charset (&local_charset)
       && local_charset) {
     /* we're not in an UTF-8 environment. */
-    const gchar *fname = xml_file_check_encoding(filename,local_charset, ctx);
+    char *fname = xml_file_check_encoding(filename, local_charset, ctx);
     if (fname != filename) {
       /* We've got a corrected file to parse. */
-      ret = xmlDoParseFile(fname, &error_xml);
-      unlink(fname);
+      ret = xmlDoParseFile (fname, &error_xml);
+      unlink (fname);
       /* printf("has read %s instead of %s\n",fname,filename); */
-      g_free((void *)fname);
     } else {
       /* the XML file is good. libxml is "old enough" to handle it correctly.
        */
-      ret = xmlDoParseFile(filename, &error_xml);
+      ret = xmlDoParseFile (filename, &error_xml);
     }
+    g_clear_pointer (&fname, g_free);
   } else {
-    ret = xmlDoParseFile(filename, &error_xml);
+    ret = xmlDoParseFile (filename, &error_xml);
   }
-  if (error_xml)
+
+  if (error_xml) {
     dia_context_add_message (ctx, "%s", error_xml->message);
+  }
+
   return ret;
 }
 
@@ -921,7 +953,7 @@ data_string(DataNode data, DiaContext *ctx)
     *p = 0;
     xmlFree(val);
     str2 = g_strdup(str);  /* to remove the extra space */
-    g_free(str);
+    g_clear_pointer (&str, g_free);
     return str2;
   }
 
@@ -946,6 +978,7 @@ data_string(DataNode data, DiaContext *ctx)
   return NULL;
 }
 
+
 /*!
  * \brief Return the value of a filename-type data node.
  * @param data The data node to read from.
@@ -964,15 +997,17 @@ data_filename(DataNode data, DiaContext *ctx)
 
   if (utf8) {
     GError *error = NULL;
-    if ((filename = g_filename_from_utf8(utf8, -1, NULL, NULL, &error)) == NULL) {
+    if ((filename = g_filename_from_utf8 (utf8, -1, NULL, NULL, &error)) == NULL) {
       dia_context_add_message (ctx, "%s", error->message);
-      g_error_free (error);
+      g_clear_error (&error);
     }
-    g_free(utf8);
+    g_clear_pointer (&utf8, g_free);
   }
+
   return filename;
 }
 
+
 /*!
  * \brief Return the value of a font-type data node.
  *
@@ -1207,7 +1242,7 @@ data_add_point(AttributeNode attr, const Point *point, DiaContext *ctx)
 
   data_node = xmlNewChild(attr, NULL, (const xmlChar *)"point", NULL);
   xmlSetProp(data_node, (const xmlChar *)"val", (xmlChar *)buffer);
-  g_free(buffer);
+  g_clear_pointer (&buffer, g_free);
 }
 
 /*!
@@ -1237,14 +1272,14 @@ data_add_bezpoint(AttributeNode attr, const BezPoint *point, DiaContext *ctx)
 
   buffer = _str_point (&point->p1);
   xmlSetProp(data_node, (const xmlChar *)"p1", (xmlChar *)buffer);
-  g_free (buffer);
+  g_clear_pointer (&buffer, g_free);
   if (point->type == BEZ_CURVE_TO) {
     buffer = _str_point (&point->p2);
     xmlSetProp(data_node, (const xmlChar *)"p2", (xmlChar *)buffer);
-    g_free (buffer);
+    g_clear_pointer (&buffer, g_free);
     buffer = _str_point (&point->p3);
     xmlSetProp(data_node, (const xmlChar *)"p3", (xmlChar *)buffer);
-    g_free (buffer);
+    g_clear_pointer (&buffer, g_free);
   }
 }
 
@@ -1275,7 +1310,7 @@ data_add_rectangle(AttributeNode attr, const DiaRectangle *rect, DiaContext *ctx
   data_node = xmlNewChild(attr, NULL, (const xmlChar *)"rectangle", NULL);
   xmlSetProp(data_node, (const xmlChar *)"val", (xmlChar *)buffer);
 
-  g_free(buffer);
+  g_clear_pointer (&buffer, g_free);
 }
 
 /*!
@@ -1304,7 +1339,7 @@ data_add_string(AttributeNode attr, const char *str, DiaContext *ctx)
 
     (void)xmlNewChild(attr, NULL, (const xmlChar *)"string", (xmlChar *) sharped_str);
 
-    g_free(sharped_str);
+    g_clear_pointer (&sharped_str, g_free);
 }
 
 /*!
@@ -1322,7 +1357,7 @@ data_add_filename(DataNode data, const char *str, DiaContext *ctx)
 
   data_add_string(data, utf8, ctx);
 
-  g_free(utf8);
+  g_clear_pointer (&utf8, g_free);
 }
 
 /*!
diff --git a/lib/diaarrowchooser.c b/lib/diaarrowchooser.c
index daccce81..340fd71b 100644
--- a/lib/diaarrowchooser.c
+++ b/lib/diaarrowchooser.c
@@ -231,7 +231,7 @@ dia_arrow_preview_expose(GtkWidget *widget, GdkEventExpose *event)
                   linewidth, &color_fg, &color_bg);
     }
     dia_renderer_end_render (DIA_RENDERER (renderer));
-    g_object_unref (renderer);
+    g_clear_object (&renderer);
 
     ctx = gdk_cairo_create (win);
     cairo_set_source_surface (ctx, surface, x, y);
diff --git a/lib/diacolorselector.c b/lib/diacolorselector.c
index 2271018c..88848f36 100644
--- a/lib/diacolorselector.c
+++ b/lib/diacolorselector.c
@@ -208,7 +208,7 @@ more_colours (DiaColorSelector *cs)
   for (tmplist = persistent_list_get_glist (PERSIST_NAME);
         tmplist != NULL;
         tmplist = g_list_next (tmplist)) {
-    gchar *spec;
+    char *spec;
     Color colour;
 
     dia_colour_parse (&colour, tmplist->data);
@@ -220,7 +220,7 @@ more_colours (DiaColorSelector *cs)
     g_string_append (palette, spec);
     g_string_append (palette, ":");
 
-    g_free (spec);
+    g_clear_pointer (&spec, g_free);
   }
 
   g_object_set (gtk_widget_get_settings (GTK_WIDGET (colorsel)),
@@ -515,10 +515,11 @@ dia_color_selector_set_color (GtkWidget   *widget,
                         COL_TEXT, text,
                         -1);
 
-    g_free (text);
+    g_clear_pointer (&text, g_free);
 
     gtk_combo_box_set_active_iter (GTK_COMBO_BOX (cs->combo), &iter);
   }
+
   cs->looking_for = NULL;
   cs->found = FALSE;
 }
diff --git a/lib/diacontext.c b/lib/diacontext.c
index 7d807964..504d0e3f 100644
--- a/lib/diacontext.c
+++ b/lib/diacontext.c
@@ -1,7 +1,7 @@
 /* dia -- an diagram creation/manipulation program
  * Copyright (C) 1998 Alexander Larsson
  *
- * diacontext.c -- 
+ * diacontext.c --
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -64,12 +64,14 @@ _dia_context_finalize(GObject *object)
 
   g_list_foreach (context->messages, (GFunc) g_free, NULL);
   g_list_free (context->messages);
-  g_free (context->desc);
-  g_free (context->filename);
+  g_clear_pointer (&context->desc, g_free);
+  g_clear_pointer (&context->filename, g_free);
 
   G_OBJECT_CLASS (parent_class)->finalize (object);
 }
-static void 
+
+
+static void
 _dia_context_class_init(DiaContextClass *klass)
 {
   GObjectClass *object_class = G_OBJECT_CLASS (klass);
@@ -77,7 +79,9 @@ _dia_context_class_init(DiaContextClass *klass)
   parent_class = g_type_class_peek_parent (klass);
   object_class->finalize = _dia_context_finalize;
 }
-static void 
+
+
+static void
 _dia_context_init(DiaContext *self)
 {
   /* zero initialization should be right */
@@ -91,18 +95,21 @@ dia_context_new (const char *desc)
   return context;
 }
 
-void 
+
+void
 dia_context_release (DiaContext *context)
 {
   /* FIXME: this should vanish */
-  if (context->messages)
-    message_warning ("%s:\n%s", 
+  if (context->messages) {
+    message_warning ("%s:\n%s",
                      context->desc ? context->desc : "<no context>",
                      (char *) context->messages->data);
+  }
 
-  g_object_unref (G_OBJECT (context));
+  g_object_unref (context);
 }
 
+
 /*!
  * \brief Clean out the context for further use
  */
@@ -112,20 +119,17 @@ dia_context_reset (DiaContext *context)
   g_list_foreach (context->messages, (GFunc) g_free, NULL);
   g_list_free (context->messages);
   context->messages = NULL;
-  g_free (context->desc);
-  context->desc = NULL;
-  g_free (context->filename);
-  context->filename = NULL;
+  g_clear_pointer (&context->desc, g_free);
+  g_clear_pointer (&context->filename, g_free);
 }
 
-void 
-dia_context_set_filename (DiaContext *context, 
+void
+dia_context_set_filename (DiaContext *context,
                          const char *filename)
 {
   g_return_if_fail (context != NULL);
 
-  if (context->filename)
-    g_free (context->filename);
+  g_clear_pointer (&context->filename, g_free);
   context->filename = g_strdup (filename);
 }
 
@@ -146,8 +150,8 @@ dia_context_get_filename (DiaContext *context)
   return context->filename ? context->filename : "?";
 }
 
-void 
-dia_context_add_message (DiaContext *context, 
+void
+dia_context_add_message (DiaContext *context,
                         const char *format, ...)
 {
   gchar *msg;
@@ -162,16 +166,16 @@ dia_context_add_message (DiaContext *context,
   msg = g_strdup_vprintf (format, args);
   va_end (args);
   /* ToDo: dont repeat the same message over and over again, except ... */
-  
+
   context->messages = g_list_prepend (context->messages, msg);
 }
 
-void 
+void
 dia_context_add_message_with_errno (DiaContext *context, int nr,
                                    const char *format, ...)
 {
-  gchar *errstr;
-  gchar *msg;
+  char *errstr;
+  char *msg;
   va_list args;
 
   g_return_if_fail (context != NULL);
@@ -183,13 +187,13 @@ dia_context_add_message_with_errno (DiaContext *context, int nr,
 
   errstr = (nr == 0) ? NULL : g_locale_to_utf8 (strerror(nr), -1, NULL, NULL, NULL);
   if (errstr) {
-    gchar *tmp = g_strdup_printf ("%s\n%s", msg, errstr);
-    
-    g_free (msg);
+    char *tmp = g_strdup_printf ("%s\n%s", msg, errstr);
+
+    g_clear_pointer (&msg, g_free);
     msg = tmp;
   }
   /* ToDo: dont repeat the same message over and over again, except ... */
 
   context->messages = g_list_prepend (context->messages, msg);
-  g_free (errstr);
+  g_clear_pointer (&errstr, g_free);
 }
diff --git a/lib/diafontselector.c b/lib/diafontselector.c
index 4647b927..c5ecd6bb 100644
--- a/lib/diafontselector.c
+++ b/lib/diafontselector.c
@@ -173,12 +173,12 @@ get_family_from_name (GtkWidget *widget, const gchar *fontname)
   for (i = 0; i < n_families; i++) {
     if (!(g_ascii_strcasecmp (pango_font_family_get_name (families[i]), fontname))) {
       PangoFontFamily *fam = families[i];
-      g_free (families);
+      g_clear_pointer (&families, g_free);
       return fam;
     }
   }
   g_warning (_("Couldn't find font family for %s\n"), fontname);
-  g_free (families);
+  g_clear_pointer (&families, g_free);
   return NULL;
 }
 
@@ -222,7 +222,7 @@ set_styles (DiaFontSelector *fs,
     pango_font_description_free (pfd);
   }
 
-  g_free (faces);
+  g_clear_pointer (&faces, g_free);
 
   if (stylebits == 0) {
     g_warning ("'%s' has no style!",
@@ -355,7 +355,7 @@ font_changed (GtkComboBox     *widget,
 
   gtk_tree_path_free (path);
   gtk_tree_path_free (active_path);
-  g_free (family);
+  g_clear_pointer (&family, g_free);
 }
 
 
@@ -371,7 +371,7 @@ is_separator (GtkTreeModel *model,
 
   result = g_strcmp0 (family, "separator") == 0;
 
-  g_free (family);
+  g_clear_pointer (&family, g_free);
 
   return result;
 }
@@ -541,7 +541,7 @@ dia_font_selector_init (DiaFontSelector *fs)
                         FONT_COL_FAMILY, pango_font_family_get_name (families[i]),
                         -1);
   }
-  g_free (families);
+  g_clear_pointer (&families, g_free);
 
   gtk_box_pack_start (GTK_BOX (fs), GTK_WIDGET (priv->fonts), FALSE, TRUE, 0);
   gtk_box_pack_start (GTK_BOX (fs), GTK_WIDGET (priv->styles), FALSE, TRUE, 0);
@@ -576,7 +576,7 @@ set_font (GtkTreeModel *model,
     gtk_combo_box_set_active_iter (GTK_COMBO_BOX (priv->fonts), iter);
   }
 
-  g_free (font);
+  g_clear_pointer (&font, g_free);
 
   return res;
 }
@@ -638,7 +638,7 @@ dia_font_selector_get_font (DiaFontSelector *self)
 
   font = dia_font_new (fontname, style, 1.0);
 
-  g_free (fontname);
+  g_clear_pointer (&fontname, g_free);
 
   return font;
 }
diff --git a/lib/diagramdata.c b/lib/diagramdata.c
index 5c02c059..1aadd2c8 100644
--- a/lib/diagramdata.c
+++ b/lib/diagramdata.c
@@ -126,7 +126,7 @@ diagram_data_init(DiagramData *data)
 
   first_layer = dia_layer_new (_("Background"), data);
 
-  data->layers = g_ptr_array_new ();
+  data->layers = g_ptr_array_new_with_free_func (g_object_unref);
   g_ptr_array_add (data->layers, first_layer);
   data->active_layer = first_layer;
 
@@ -150,13 +150,8 @@ diagram_data_finalize (GObject *object)
 {
   DiagramData *data = DIA_DIAGRAM_DATA (object);
 
-  guint i;
-
-  g_free (data->paper.name);
+  g_clear_pointer (&data->paper.name, g_free);
 
-  for (i=0;i<data->layers->len;i++) {
-    g_object_unref (g_ptr_array_index (data->layers, i));
-  }
   g_ptr_array_free (data->layers, TRUE);
   data->active_layer = NULL;
 
@@ -192,7 +187,7 @@ diagram_data_clone (DiagramData *data)
   clone->paper.name = g_strdup (data->paper.name);
   clone->is_compressed = data->is_compressed;
 
-  g_object_unref (g_ptr_array_index (clone->layers, 0));
+  g_ptr_array_remove_index (clone->layers, 0);
   g_ptr_array_remove (clone->layers, clone->active_layer);
 
   for (i=0; i < data->layers->len; ++i) {
@@ -510,16 +505,22 @@ data_highlight_add(DiagramData *data, DiaObject *obj, DiaHighlightType type)
   data->highlighted = g_list_prepend(data->highlighted, oh);
 }
 
+
 void
-data_highlight_remove(DiagramData *data, DiaObject *obj)
+data_highlight_remove (DiagramData *data, DiaObject *obj)
 {
   ObjectHighlight *oh;
-  if (!(oh = find_object_highlight (data->highlighted, obj)))
+
+  if (!(oh = find_object_highlight (data->highlighted, obj))) {
     return; /* should this be an error?`*/
-  data->highlighted = g_list_remove(data->highlighted, oh);
-  g_free(oh);
+  }
+
+  data->highlighted = g_list_remove (data->highlighted, oh);
+
+  g_clear_pointer (&oh, g_free);
 }
 
+
 DiaHighlightType
 data_object_get_highlight(DiagramData *data, DiaObject *obj)
 {
diff --git a/lib/diaimportrenderer.c b/lib/diaimportrenderer.c
index 951f8d87..a07ccf43 100644
--- a/lib/diaimportrenderer.c
+++ b/lib/diaimportrenderer.c
@@ -720,6 +720,7 @@ is_capable_to (DiaRenderer *renderer, RenderCapability cap)
   return TRUE;
 }
 
+
 /*!
  * \brief Remember the pattern for later reference
  * \memberof _DiaImportRenderer
@@ -728,12 +729,13 @@ static void
 set_pattern (DiaRenderer *renderer, DiaPattern *pat)
 {
   DiaImportRenderer *self = DIA_IMPORT_RENDERER (renderer);
+
   if (self->pattern && self->pattern != pat) {
-    g_object_unref (self->pattern);
-    self->pattern = g_object_ref (pat);
+    g_set_object (&self->pattern, pat);
   }
 }
 
+
 /*!
  * \brief Take ownership of the objects created so far
  * This function return a _Group object containing all DiaObject created
diff --git a/lib/dialib.c b/lib/dialib.c
index b61ede27..a312c9c1 100644
--- a/lib/dialib.c
+++ b/lib/dialib.c
@@ -35,27 +35,26 @@
 #include "properties.h" /* stdprops_init() */
 #include "standard-path.h"
 
-static void
-stderr_message_internal(const char *title, enum ShowAgainStyle showAgain,
-                       const char *fmt, va_list args,  va_list args2) G_GNUC_PRINTF(3, 0);
 
 static void
-stderr_message_internal(const char *title, enum ShowAgainStyle showAgain,
-                       const char *fmt, va_list args,  va_list args2)
+stderr_message_internal (const char          *title,
+                         enum ShowAgainStyle  showAgain,
+                         const char          *fmt,
+                         va_list              args,
+                         va_list              args2)
 {
-  static gchar *buf = NULL;
-  static gint   alloc = 0;
-  gint len;
+  static char *buf = NULL;
+  static int   alloc = 0;
+  int len;
 
   len = g_printf_string_upper_bound (fmt, args);
 
   if (len >= alloc) {
-    if (buf)
-      g_free (buf);
+    g_clear_pointer (&buf, g_free);
 
-    alloc = nearest_pow (MAX(len + 1, 1024));
+    alloc = nearest_pow (MAX (len + 1, 1024));
 
-    buf = g_new (char, alloc);
+    buf = g_new0 (char, alloc);
   }
 
   vsprintf (buf, fmt, args2);
@@ -63,6 +62,7 @@ stderr_message_internal(const char *title, enum ShowAgainStyle showAgain,
   g_printerr ("%s: %s\n", title, buf);
 }
 
+
 #ifdef G_OS_WIN32
 static void
 myXmlErrorReporting (void *ctx, const char* msg, ...)
@@ -75,7 +75,7 @@ myXmlErrorReporting (void *ctx, const char* msg, ...)
   g_printerr ("%s", string ? string : "xml error (null)?");
   va_end(args);
 
-  g_free(string);
+  g_clear_pointer (&string, g_free);
 }
 #endif
 
@@ -118,7 +118,7 @@ libdia_init (guint flags)
     diagtkrc = dia_config_filename("diagtkrc");
     dia_log_message ("Config from %s", diagtkrc);
     gtk_rc_parse(diagtkrc);
-    g_free(diagtkrc);
+    g_clear_pointer (&diagtkrc, g_free);
 
     color_init();
   }
diff --git a/lib/diapathrenderer.c b/lib/diapathrenderer.c
index cf8e2038..045b16f4 100644
--- a/lib/diapathrenderer.c
+++ b/lib/diapathrenderer.c
@@ -842,7 +842,7 @@ create_standard_path_from_object (DiaObject *obj)
       path = group_create (list);
     }
   }
-  g_object_unref (renderer);
+  g_clear_object (&renderer);
 
   return path;
 }
diff --git a/lib/diapatternselector.c b/lib/diapatternselector.c
index 7b92a66f..dd9572fe 100644
--- a/lib/diapatternselector.c
+++ b/lib/diapatternselector.c
@@ -19,7 +19,7 @@
  * along with this program; if not, write to the Free Software
  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  */
-#include <config.h> 
+#include <config.h>
 
 #include "diapatternselector.h"
 #include "intl.h"
@@ -48,14 +48,16 @@ static guint dia_patternsel_signals[DIA_PATTERNSEL_LAST_SIGNAL] = { 0 };
 
 static DiaPattern *_create_preset_pattern (guint n);
 
+
 static void
-dia_pattern_selector_finalize(GObject* object)
+dia_pattern_selector_finalize(GObject *object)
 {
-  DiaPatternSelector *ps = (DiaPatternSelector *)object;
-  if (ps->pattern)
-    g_object_unref (ps->pattern);
+  DiaPatternSelector * ps = (DiaPatternSelector *)object;
+
+  g_clear_object (&ps->pattern);
 }
 
+
 static void
 dia_pattern_selector_class_init (DiaPatternSelectorClass *klass)
 {
@@ -72,10 +74,11 @@ dia_pattern_selector_class_init (DiaPatternSelectorClass *klass)
 }
 
 static GType dia_pattern_selector_get_type (void);
- 
+
 G_DEFINE_TYPE (DiaPatternSelector, dia_pattern_selector, GTK_TYPE_HBOX);
 
-/* GUI stuff - not completely done yet 
+
+/* GUI stuff - not completely done yet
    - add/remove color stops
    - toggle between radial/linear
    - have some visual representation of the gradient
@@ -83,20 +86,21 @@ G_DEFINE_TYPE (DiaPatternSelector, dia_pattern_selector, GTK_TYPE_HBOX);
      horizontal/vertical/radial, ...
  */
 static void
-_pattern_toggled(GtkWidget *wid, DiaPatternSelector *ps)
+_pattern_toggled (GtkWidget *wid, DiaPatternSelector *ps)
 {
-  if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(wid))) {
-    gtk_label_set_text(GTK_LABEL(gtk_bin_get_child(GTK_BIN(wid))), _("Yes"));
+  if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (wid))) {
+    gtk_label_set_text (GTK_LABEL (gtk_bin_get_child (GTK_BIN (wid))), _("Yes"));
     if (!ps->pattern)
       ps->pattern = _create_preset_pattern (0);
   } else {
-    gtk_label_set_text(GTK_LABEL(gtk_bin_get_child(GTK_BIN(wid))), _("No"));
-    if (ps->pattern)
-      g_object_unref (ps->pattern);
-    ps->pattern = NULL;
+    gtk_label_set_text (GTK_LABEL (gtk_bin_get_child (GTK_BIN (wid))), _("No"));
+    g_clear_object (&ps->pattern);
   }
+
   g_signal_emit (G_OBJECT (ps), dia_patternsel_signals[DIA_PATTERNSEL_VALUE_CHANGED], 0);
 }
+
+
 /*! Create the pattern preset pop-up menu */
 typedef enum {
   LEFT = 0x1,
@@ -143,7 +147,7 @@ _create_preset_pattern (guint n)
   color = attributes_get_foreground ();
   dia_pattern_add_color (pat, 1.0, &color);
 
-  return pat; 
+  return pat;
 }
 
 #define PRESET_KEY "preset-pattern-key"
@@ -152,14 +156,15 @@ static void
 _pattern_activate_preset(GtkWidget *widget, gpointer data)
 {
   DiaPatternSelector *ps = (DiaPatternSelector *)data;
-  guint n = GPOINTER_TO_UINT(g_object_get_data (G_OBJECT(widget), PRESET_KEY));
-  if (ps->pattern)
-    g_object_unref (ps->pattern);
-  ps->pattern = _create_preset_pattern (n);
-  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(ps->state), ps->pattern != NULL);
+  guint n = GPOINTER_TO_UINT (g_object_get_data (G_OBJECT (widget), PRESET_KEY));
+
+  g_set_object (&ps->pattern, _create_preset_pattern (n));
+
+  gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ps->state), ps->pattern != NULL);
   g_signal_emit (G_OBJECT (ps), dia_patternsel_signals[DIA_PATTERNSEL_VALUE_CHANGED], 0);
 }
 
+
 static gint
 _popup_button_press(GtkWidget *widget, GdkEventButton *event, gpointer data)
 {
diff --git a/lib/diarenderer.c b/lib/diarenderer.c
index ab059461..38d85de9 100644
--- a/lib/diarenderer.c
+++ b/lib/diarenderer.c
@@ -289,8 +289,11 @@ draw_object (DiaRenderer *renderer,
   if (matrix) {
 #if 1
     DiaRenderer *tr = dia_transform_renderer_new (renderer);
+
     dia_renderer_draw_object (tr, object, matrix);
-    g_object_unref (tr);
+
+    g_clear_object (&tr);
+
     return;
 #else
     /* visual complaints - not completely correct */
@@ -326,9 +329,8 @@ dia_renderer_finalize (GObject *object)
   g_clear_object (&priv->font);
 
   if (priv->bezier) {
-    if (priv->bezier->points)
-      g_free (priv->bezier->points);
-    g_free (priv->bezier);
+    g_clear_pointer (&priv->bezier->points, g_free);
+    g_clear_pointer (&priv->bezier, g_free);
   }
 
   G_OBJECT_CLASS (dia_renderer_parent_class)->finalize (object);
@@ -1906,7 +1908,8 @@ get_text_width (DiaRenderer *renderer,
     char *str = g_strndup (text, length);
 
     ret = dia_font_string_width (str, font, font_height);
-    g_free (str);
+
+    g_clear_pointer (&str, g_free);
   } else {
     g_warning ("%s::get_text_width not implemented (and font == NULL)!",
                G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
diff --git a/lib/diasvgrenderer.c b/lib/diasvgrenderer.c
index 31beeb47..87613b0f 100644
--- a/lib/diasvgrenderer.c
+++ b/lib/diasvgrenderer.c
@@ -149,9 +149,9 @@ _gradient_do (gpointer key,
   }
   /* don't miss to set the id */
   {
-    gchar *id = _make_pattern_key (pattern);
+    char *id = _make_pattern_key (pattern);
     xmlSetProp (gradient, (const xmlChar *)"id", (const xmlChar *)id);
-    g_free (id);
+    g_clear_pointer (&id, g_free);
   }
   if (flags & DIA_PATTERN_USER_SPACE)
     xmlSetProp (gradient, (const xmlChar *)"gradientUnits", (const xmlChar *)"userSpaceOnUse");
@@ -177,7 +177,7 @@ static void
 end_render(DiaRenderer *self)
 {
   DiaSvgRenderer *renderer = DIA_SVG_RENDERER (self);
-  g_free(renderer->linestyle);
+  g_clear_pointer (&renderer->linestyle, g_free);
 
   /* handle potential patterns */
   if (renderer->patterns) {
@@ -191,7 +191,7 @@ end_render(DiaRenderer *self)
   }
   xmlSetDocCompressMode(renderer->doc, 0);
   xmlDiaSaveFile(renderer->filename, renderer->doc);
-  g_free(renderer->filename);
+  g_clear_pointer (&renderer->filename, g_free);
   xmlFreeDoc(renderer->doc);
 }
 
@@ -296,7 +296,7 @@ set_linestyle(DiaRenderer *self, LineStyle mode, real dash_length)
     dash_length = 0.001;
   dot_length = dash_length*0.2;
 
-  g_free (renderer->linestyle);
+  g_clear_pointer (&renderer->linestyle, g_free);
   switch (mode) {
     case LINESTYLE_SOLID:
       renderer->linestyle = NULL;
@@ -381,8 +381,7 @@ set_pattern(DiaRenderer *self, DiaPattern *pattern)
     renderer->active_pattern = NULL;
   }
 
-  if (prev)
-    g_object_unref (prev);
+  g_clear_object (&prev);
 }
 
 /*!
@@ -410,7 +409,7 @@ get_draw_style(DiaSvgRenderer *renderer,
     if (renderer->active_pattern) {
       gchar *key = _make_pattern_key (renderer->active_pattern);
       g_string_printf(str, "fill:url(#%s)", key);
-      g_free (key);
+      g_clear_pointer (&key, g_free);
     } else {
       g_string_printf(str, "fill: #%02x%02x%02x; fill-opacity: %s",
                      (int)(255*fill->red), (int)(255*fill->green),
@@ -903,14 +902,14 @@ draw_image(DiaRenderer *self,
     if (!uri)
       uri = g_strdup ("(null)");
     xmlSetProp(node, (const xmlChar *)"xlink:href", (xmlChar *) uri);
-    g_free (prefix);
+    g_clear_pointer (&prefix, g_free);
   } else if ((uri = dia_relativize_filename (renderer->filename, dia_image_filename(image))) != NULL)
     xmlSetProp(node, (const xmlChar *)"xlink:href", (xmlChar *) uri);
   else if ((uri = g_filename_to_uri(dia_image_filename(image), NULL, NULL)) != NULL)
     xmlSetProp(node, (const xmlChar *)"xlink:href", (xmlChar *) uri);
   else /* not sure if this fallback is better than nothing */
     xmlSetProp(node, (const xmlChar *)"xlink:href", (xmlChar *) dia_image_filename(image));
-  g_free (uri);
+  g_clear_pointer (&uri, g_free);
 }
 
 /*!
diff --git a/lib/diatransformrenderer.c b/lib/diatransformrenderer.c
index ea50a74d..b1b98d0b 100644
--- a/lib/diatransformrenderer.c
+++ b/lib/diatransformrenderer.c
@@ -76,6 +76,8 @@ dia_transform_renderer_init (DiaTransformRenderer *self)
 {
   self->matrices = g_queue_new ();
 }
+
+
 /*!
  * \brief Destructor
  * If there are still matrices left, deallocate them
@@ -88,9 +90,10 @@ dia_path_renderer_finalize (GObject *object)
 
   g_queue_free (self->matrices);
   /* drop our reference */
-  g_object_unref (self->worker);
+  g_clear_object (&self->worker);
 }
 
+
 /*!
  * \brief Starting a new rendering run
  * Should not be called because this renderer is intermediate.
diff --git a/lib/dynamic_obj.c b/lib/dynamic_obj.c
index 1673eb76..1eea807f 100644
--- a/lib/dynamic_obj.c
+++ b/lib/dynamic_obj.c
@@ -40,22 +40,26 @@ void dynobj_list_add_object(DiaObject* obj, guint timeout) {
 static gint dor_found(gconstpointer data, gconstpointer user_data) {
     const DynobjRec* dor = (const DynobjRec*)data;
     const DiaObject* obj = (const DiaObject*)user_data;
-    
+
     if ((!dor) || (!obj)) return 1;
     if (dor->obj != obj) return 1;
     return 0;
 }
-                          
-void dynobj_list_remove_object(DiaObject* obj) {
-    GList* item = g_list_find_custom(dyn_obj_list,obj,dor_found);
-
-    if (item) {
-        DynobjRec* dor = item->data;
-        dyn_obj_list = g_list_remove(dyn_obj_list,dor);
-        g_free(dor);
-    }
+
+
+void
+dynobj_list_remove_object (DiaObject *obj)
+{
+  GList* item = g_list_find_custom (dyn_obj_list, obj, dor_found);
+
+  if (item) {
+    DynobjRec* dor = item->data;
+    dyn_obj_list = g_list_remove(dyn_obj_list,dor);
+    g_clear_pointer (&dor, g_free);
+  }
 }
 
+
 typedef struct {
     ObjectDynobjFunc odf;
     gpointer data;
@@ -80,7 +84,7 @@ static void accum_timeout(gpointer data, gpointer user_data) {
     DynobjRec* dor = (DynobjRec*)data;
 
     if (!dor) return;
-    
+
     *accum = MAX(*accum,dor->timeout);
 }
 
diff --git a/lib/font-height.c b/lib/font-height.c
index 177864ad..88ad3082 100644
--- a/lib/font-height.c
+++ b/lib/font-height.c
@@ -73,26 +73,28 @@ dump_font_sizes (PangoContext *context, FILE *f, guint flags)
       font = pango_context_load_font (context, pfd);
       if (font) {
         PangoFontMetrics *metrics = pango_font_get_metrics (font, NULL);
-       /* now make a font-size where the font/line-height matches the given pixel size */
-       real total = ((double)pango_font_metrics_get_ascent (metrics)
-                           + pango_font_metrics_get_descent (metrics)) / PANGO_SCALE;
-       real factor = height*pixels_per_cm/total;
-       real line_height;
+        /* now make a font-size where the font/line-height matches the given pixel size */
+        double total = ((double) pango_font_metrics_get_ascent (metrics)
+                             + pango_font_metrics_get_descent (metrics)) / PANGO_SCALE;
+        double factor = height*pixels_per_cm/total;
+        double line_height;
 
         if (flags & DUMP_ABSOLUTE)
           pango_font_description_set_absolute_size (pfd, factor * height * pixels_per_cm * PANGO_SCALE);
-       else
+        else {
           pango_font_description_set_size (pfd, factor * height * pixels_per_cm * PANGO_SCALE);
-       pango_font_metrics_unref (metrics);
-       g_object_unref (font);
+        }
 
-       font = pango_context_load_font (context, pfd);
-       metrics = pango_font_get_metrics (font, NULL);
+        pango_font_metrics_unref (metrics);
+        g_clear_object (&font);
 
-       line_height = ((double)pango_font_metrics_get_ascent (metrics)
-                            + pango_font_metrics_get_descent (metrics)) / PANGO_SCALE;
-        fprintf (f, "\t%.3g",  flags & DUMP_FACTORS ? factor : line_height);
-       g_object_unref (font);
+        font = pango_context_load_font (context, pfd);
+        metrics = pango_font_get_metrics (font, NULL);
+
+        line_height = ((double) pango_font_metrics_get_ascent (metrics)
+                              + pango_font_metrics_get_descent (metrics)) / PANGO_SCALE;
+        fprintf (f, "\t%.3g", flags & DUMP_FACTORS ? factor : line_height);
+        g_clear_object (&font);
       }
       pango_font_description_free (pfd);
     }
diff --git a/lib/font.c b/lib/font.c
index 624f435d..16b42158 100644
--- a/lib/font.c
+++ b/lib/font.c
@@ -69,23 +69,27 @@ struct _DiaFont
  */
 static real global_zoom_factor = 20.0;
 
+
 static void
-dia_font_check_for_font(int font)
+dia_font_check_for_font (int font)
 {
   DiaFont *check;
   PangoFont *loaded;
-  static real height = 1.0;
+  static double height = 1.0;
+
+  check = dia_font_new_from_style (font, height);
+  loaded = pango_context_load_font (dia_font_get_context (), check->pfd);
 
-  check = dia_font_new_from_style(font, height);
-  loaded = pango_context_load_font(dia_font_get_context(), check->pfd);
   if (!loaded) {
-    message_error(_("Can't load font %s.\n"), dia_font_get_family(check));
+    message_error (_("Can't load font %s.\n"), dia_font_get_family (check));
   } else {
-    g_object_unref(loaded);
+    g_clear_object (&loaded);
   }
+
   g_clear_object (&check);
 }
 
+
 void
 dia_font_init(PangoContext* pcontext)
 {
@@ -114,7 +118,7 @@ dia_font_push_context (PangoContext *pcontext)
 void
 dia_font_pop_context (void)
 {
-  g_object_unref (pango_context);
+  g_clear_object (&pango_context);
   pango_context = (PangoContext*) pango_contexts->data;
   pango_context_set_language (pango_context, gtk_get_default_language ());
   pango_contexts = g_list_next (pango_contexts);
@@ -232,9 +236,10 @@ _dia_font_adjust_size (DiaFont *font, real height, gboolean recalc_alwways)
     dia_pfd_set_height (font->pfd, height);
     /* need to load a font to get it's metrics */
     loaded = font->loaded;
-    font->loaded = pango_context_load_font(dia_font_get_context(), font->pfd);
-    if (loaded) /* drop old reference */
-      g_object_unref (loaded);
+    font->loaded = pango_context_load_font (dia_font_get_context (), font->pfd);
+
+    g_clear_object (&loaded);
+
     if (font->metrics)
       pango_font_metrics_unref (font->metrics);
 
@@ -363,23 +368,25 @@ DiaFont* dia_font_copy(const DiaFont* font)
                       dia_font_get_height(font));
 }
 
+
 void
-dia_font_finalize(GObject* object)
+dia_font_finalize(GObject *object)
 {
-  DiaFont* font = DIA_FONT(object);
+  DiaFont *font = DIA_FONT (object);
 
   if (font->pfd)
-    pango_font_description_free(font->pfd);
+    pango_font_description_free (font->pfd);
   font->pfd = NULL;
   if (font->metrics)
-    pango_font_metrics_unref(font->metrics);
+    pango_font_metrics_unref (font->metrics);
   font->metrics = NULL;
-  if (font->loaded)
-    g_object_unref(font->loaded);
-  font->loaded = NULL;
-  G_OBJECT_CLASS(parent_class)->finalize(object);
+
+  g_clear_object (&font->loaded);
+
+  G_OBJECT_CLASS (parent_class)->finalize (object);
 }
 
+
 DiaFontStyle
 dia_font_get_style(const DiaFont* font)
 {
@@ -476,24 +483,22 @@ dia_font_set_any_family(DiaFont* font, const char* family)
   pango_font_description_set_family(font->pfd, family);
   if (changed) /* force recalculation on name change */
     _dia_font_adjust_size (font, font->height, TRUE);
-  if (font->legacy_name) {
-    g_free(font->legacy_name);
-    font->legacy_name = NULL;
-  }
+
+  g_clear_pointer (&font->legacy_name, g_free);
 }
 
+
 void
-dia_font_set_family(DiaFont* font, DiaFontFamily family)
+dia_font_set_family  (DiaFont *font, DiaFontFamily family)
 {
-  g_return_if_fail(font != NULL);
+  g_return_if_fail (font != NULL);
 
-  dia_pfd_set_family(font->pfd,family);
-  if (font->legacy_name) {
-    g_free(font->legacy_name);
-    font->legacy_name = NULL;
-  }
+  dia_pfd_set_family (font->pfd,family);
+
+  g_clear_pointer (&font->legacy_name, g_free);
 }
 
+
 void
 dia_font_set_weight(DiaFont* font, DiaFontWeight weight)
 {
@@ -813,7 +818,7 @@ dia_font_get_sizes(const char* string, DiaFont *font, real height,
   }
 
   pango_layout_iter_free(iter);
-  g_object_unref(G_OBJECT(layout));
+  g_clear_object (&layout);
 
   *ascent = bline-top;
   *descent = bottom-bline;
diff --git a/lib/group.c b/lib/group.c
index 90a880dc..d3d8aa04 100644
--- a/lib/group.c
+++ b/lib/group.c
@@ -365,20 +365,17 @@ void
 group_destroy_shallow(DiaObject *obj)
 {
   Group *group = (Group *)obj;
-  if (obj->handles)
-    g_free(obj->handles);
 
-  if (obj->connections)
-    g_free(obj->connections);
+  g_clear_pointer (&obj->handles, g_free);
+  g_clear_pointer (&obj->connections, g_free);
 
   g_list_free(group->objects);
 
   prop_desc_list_free_handler_chain((PropDescription *)group->pdesc);
-  g_free((PropDescription *)group->pdesc);
 
-  g_free (group->matrix);
-
-  g_free(group);
+  g_free ((PropDescription *) group->pdesc);
+  g_clear_pointer (&group->matrix, g_free);
+  g_clear_pointer (&group, g_free);
 }
 
 static void
@@ -392,10 +389,10 @@ group_destroy(Group *group)
      been unconnected and freed. */
   obj->num_connections = 0;
 
-  prop_desc_list_free_handler_chain((PropDescription *)group->pdesc);
-  g_free((PropDescription *)group->pdesc);
+  prop_desc_list_free_handler_chain((PropDescription *) group->pdesc);
 
-  g_free (group->matrix);
+  g_free ((PropDescription *) group->pdesc);
+  g_clear_pointer (&group->matrix, g_free);
 
   object_destroy(obj);
 }
@@ -530,7 +527,7 @@ group_create_with_matrix(GList *objects, DiaMatrix *matrix)
 
   if (dia_matrix_is_identity (matrix)) {
     /* just drop it as it has no effect */
-    g_free (matrix);
+    g_clear_pointer (&matrix, g_free);
     matrix = NULL;
   }
   group->matrix = matrix;
@@ -705,8 +702,8 @@ group_describe_props(Group *group)
          /* these are not meant to be saved/loaded with the group */
          arr[i].flags |= (PROP_FLAG_DONT_SAVE|PROP_FLAG_OPTIONAL);
        }
-       g_free ((PropDescription *)group->pdesc);
-       group->pdesc = arr;
+        g_free ((PropDescription *) group->pdesc);
+        group->pdesc = arr;
       }
     }
   }
@@ -897,7 +894,7 @@ group_prop_change_free(GroupPropChange *change)
        tmp = g_list_next(tmp)) {
     ObjectChange *obj_change = (ObjectChange*)tmp->data;
     obj_change->free(obj_change);
-    g_free(obj_change);
+    g_clear_pointer (&obj_change, g_free);
   }
   g_list_free(change->changes_per_object);
 }
diff --git a/lib/layer.c b/lib/layer.c
index 99264ccb..bc1167da 100644
--- a/lib/layer.c
+++ b/lib/layer.c
@@ -1038,10 +1038,9 @@ dia_layer_set_parent_diagram (DiaLayer    *layer,
 
   priv = dia_layer_get_instance_private (layer);
 
-  g_clear_weak_pointer (&priv->parent_diagram);
-  g_set_weak_pointer (&priv->parent_diagram, diagram);
-
-  g_object_notify_by_pspec (G_OBJECT (layer), pspecs[PROP_PARENT_DIAGRAM]);
+  if (g_set_weak_pointer (&priv->parent_diagram, diagram)) {
+    g_object_notify_by_pspec (G_OBJECT (layer), pspecs[PROP_PARENT_DIAGRAM]);
+  }
 }
 
 /**
diff --git a/lib/message.c b/lib/message.c
index 5a7e8217..10de552c 100644
--- a/lib/message.c
+++ b/lib/message.c
@@ -43,7 +43,7 @@ typedef struct {
 } DiaMessageInfo;
 
 static void
-gtk_message_toggle_repeats(GtkWidget *button, gpointer *userdata) 
+gtk_message_toggle_repeats(GtkWidget *button, gpointer *userdata)
 {
   DiaMessageInfo *msginfo = (DiaMessageInfo*)userdata;
   if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button)))
@@ -55,10 +55,10 @@ gtk_message_toggle_repeats(GtkWidget *button, gpointer *userdata)
 }
 
 static void
-gtk_message_toggle_show_again(GtkWidget *button, gpointer *userdata) 
+gtk_message_toggle_show_again(GtkWidget *button, gpointer *userdata)
 {
   DiaMessageInfo *msginfo = (DiaMessageInfo*)userdata;
-  persistence_set_boolean(msginfo->title, 
+  persistence_set_boolean(msginfo->title,
                          gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button)));
 }
 
@@ -101,12 +101,12 @@ message_create_dialog(const gchar *title, DiaMessageInfo *msginfo, gchar *buf)
                                   GTK_BUTTONS_CLOSE,
                                   "%s", buf);
   if (title) {
-    gchar *real_title;
+    char *real_title;
 
     msginfo->title = title;
     real_title = g_strdup_printf ("Dia: %s", title);
-    gtk_window_set_title (GTK_WINDOW(dialog), real_title);
-    g_free (real_title);
+    gtk_window_set_title (GTK_WINDOW (dialog), real_title);
+    g_clear_pointer (&real_title, g_free);
   }
   gtk_widget_show (dialog);
   g_signal_connect (G_OBJECT (dialog), "response",
@@ -118,18 +118,18 @@ message_create_dialog(const gchar *title, DiaMessageInfo *msginfo, gchar *buf)
                    msginfo);
 
   msginfo->repeat_label = gtk_label_new(_("There is one similar message."));
-  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))), 
+  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))),
                    msginfo->repeat_label);
 
   msginfo->show_repeats =
     gtk_check_button_new_with_label(_("Show repeated messages"));
-  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))), 
+  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))),
                    msginfo->show_repeats);
-  g_signal_connect(G_OBJECT(msginfo->show_repeats), "toggled", 
+  g_signal_connect(G_OBJECT(msginfo->show_repeats), "toggled",
                   G_CALLBACK(gtk_message_toggle_repeats), msginfo);
 
   msginfo->repeat_view = gtk_text_view_new();
-  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))), 
+  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))),
                    msginfo->repeat_view);
   gtk_text_view_set_editable(GTK_TEXT_VIEW(msginfo->repeat_view), FALSE);
 
@@ -137,14 +137,14 @@ message_create_dialog(const gchar *title, DiaMessageInfo *msginfo, gchar *buf)
   if (msginfo->repeats != NULL) {
     repeats = msginfo->repeats;
     repeats = repeats->next;
-    for (; repeats != NULL; repeats = repeats->next) { 
+    for (; repeats != NULL; repeats = repeats->next) {
       gtk_text_buffer_insert_at_cursor(textbuffer, (gchar*)repeats->data, -1);
     }
   }
 
   msginfo->no_show_again =
     gtk_check_button_new_with_label(_("Don't show this message again"));
-  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))), 
+  gtk_container_add(GTK_CONTAINER(gtk_dialog_get_content_area(GTK_DIALOG(msginfo->dialog))),
                    msginfo->no_show_again);
   g_signal_connect(G_OBJECT(msginfo->no_show_again), "toggled",
                   G_CALLBACK(gtk_message_toggle_show_again), msginfo);
@@ -175,7 +175,7 @@ gtk_message_internal(const char* title, enum ShowAgainStyle showAgain,
       /* If not showing again, just return at once */
       return;
     }
-    askForShowAgain = TRUE;    
+    askForShowAgain = TRUE;
   }
 
   if (message_hash_table == NULL) {
@@ -184,14 +184,13 @@ gtk_message_internal(const char* title, enum ShowAgainStyle showAgain,
 
   len = g_printf_string_upper_bound (fmt, args);
   if (len >= alloc) {
-    if (buf)
-      g_free (buf);
-    
-    alloc = nearest_pow (MAX(len + 1, 1024));
-    
-    buf = g_new (char, alloc);
+    g_clear_pointer (&buf, g_free);
+
+    alloc = nearest_pow (MAX (len + 1, 1024));
+
+    buf = g_new0 (char, alloc);
   }
-  
+
   vsprintf (buf, fmt, args2);
 
   msginfo = (DiaMessageInfo*)g_hash_table_lookup(message_hash_table, fmt);
@@ -240,7 +239,7 @@ gtk_message_internal(const char* title, enum ShowAgainStyle showAgain,
 
 static MessageInternal message_internal = gtk_message_internal;
 
-void 
+void
 set_message_func(MessageInternal func)
 {
   g_assert(func);
@@ -307,7 +306,9 @@ message_error(const char *format, ...)
 }
 
 static gboolean log_enabled = FALSE;
-void 
+
+
+void
 dia_log_message_enable (gboolean yes)
 {
   log_enabled = yes;
@@ -337,5 +338,6 @@ dia_log_message (const char *format, ...)
   m = t % 60; t = (t - m) / 60;
   h = t;
   g_message ("%02d:%02d:%02d.%03d - %s", (int)h, (int)m, (int)s, (int)(ms/1000), log);
-  g_free (log);
+
+  g_clear_pointer (&log, g_free);
 }
diff --git a/lib/objchange.c b/lib/objchange.c
index 35306621..738ea1c8 100644
--- a/lib/objchange.c
+++ b/lib/objchange.c
@@ -26,7 +26,7 @@ typedef struct _ObjectStateChange ObjectStateChange;
 
 struct _ObjectStateChange {
   ObjectChange obj_change;
-  
+
   GetStateFunc get_state;
   SetStateFunc set_state;
 
@@ -38,7 +38,7 @@ static void
 object_state_change_apply_revert(ObjectStateChange *change, DiaObject *obj)
 {
   ObjectState *old_state;
-  
+
   old_state = change->get_state(change->obj);
 
   change->set_state(change->obj, change->saved_state);
@@ -46,16 +46,18 @@ object_state_change_apply_revert(ObjectStateChange *change, DiaObject *obj)
   change->saved_state = old_state;
 }
 
+
 static void
-object_state_change_free(ObjectStateChange *change)
+object_state_change_free (ObjectStateChange *change)
 {
   if ((change) && (change->saved_state)) {
     if (change->saved_state->free)
       (*change->saved_state->free)(change->saved_state);
-    g_free(change->saved_state);
+    g_clear_pointer (&change->saved_state, g_free);
   }
 }
 
+
 ObjectChange *new_object_state_change(DiaObject *obj,
                                      ObjectState *old_state,
                                      GetStateFunc get_state,
@@ -66,7 +68,7 @@ ObjectChange *new_object_state_change(DiaObject *obj,
   g_return_val_if_fail (get_state != NULL && set_state != NULL, NULL);
 
   change = g_new(ObjectStateChange, 1);
-  
+
   change->obj_change.apply =
     (ObjectChangeApplyFunc) object_state_change_apply_revert;
   change->obj_change.revert =
@@ -86,7 +88,7 @@ ObjectChange *new_object_state_change(DiaObject *obj,
 typedef struct _ObjectChangeList ObjectChangeList;
 struct _ObjectChangeList {
   ObjectChange object_change;
-  
+
   GPtrArray *changes;
 };
 
@@ -95,10 +97,10 @@ _change_list_apply (ObjectChange *change_list, DiaObject *obj)
 {
   ObjectChangeList *list = (ObjectChangeList *)change_list;
   guint i;
-  
+
   for (i = 0; i < list->changes->len; ++i) {
     ObjectChange * change = (ObjectChange *)g_ptr_array_index(list->changes, i);
-    
+
     change->apply (change, obj /*?*/);
   }
 }
@@ -107,13 +109,13 @@ _change_list_revert (ObjectChange *change_list, DiaObject *obj)
 {
   ObjectChangeList *list = (ObjectChangeList *)change_list;
   guint i;
-  
+
   if (list->changes->len < 1)
     return; /* avoid overflow below */
 
   for (i = list->changes->len - 1;/* i >= 0 */; --i) {
     ObjectChange * change = (ObjectChange *)g_ptr_array_index(list->changes, i);
-    
+
     change->revert (change, obj /*?*/);
     if (i == 0)
       break; /* break here, i>=0 does not work as loop condition (it's always TRUE) */
@@ -127,13 +129,13 @@ _change_list_free (ObjectChange *change_list)
 
   for (i = 0; i < list->changes->len; ++i) {
     ObjectChange * change = (ObjectChange *)g_ptr_array_index(list->changes, i);
-    
+
     if (change->free)
       change->free (change);
   }
   g_ptr_array_free (list->changes, FALSE);
   /* must not delete the object itself, so no:
-  g_free (change_list);
+  g_clear_pointer (&change_list, g_free);
    */
 }
 /* An empty list of changes to accumulate many to one change */
@@ -141,13 +143,13 @@ ObjectChange *
 change_list_create (void)
 {
   ObjectChangeList *list = g_new (ObjectChangeList, 1);
-  
+
   list->object_change.apply  = _change_list_apply;
   list->object_change.revert = _change_list_revert;
   list->object_change.free   = _change_list_free;
-  
+
   list->changes = g_ptr_array_new ();
-  
+
   return (ObjectChange *)list;
 }
 
diff --git a/lib/object.c b/lib/object.c
index c0da438d..eacf58a5 100644
--- a/lib/object.c
+++ b/lib/object.c
@@ -74,12 +74,8 @@ object_destroy (DiaObject *obj)
 {
   object_unconnect_all (obj);
 
-  if (obj->handles)
-    g_free (obj->handles);
-  obj->handles = NULL;
-  if (obj->connections)
-    g_free (obj->connections);
-  obj->connections = NULL;
+  g_clear_pointer (&obj->handles, g_free);
+  g_clear_pointer (&obj->connections, g_free);
   if (obj->meta)
     g_hash_table_destroy (obj->meta);
   obj->meta = NULL;
@@ -116,16 +112,16 @@ object_copy (DiaObject *from, DiaObject *to)
   to->bounding_box = from->bounding_box;
 
   to->num_handles = from->num_handles;
-  if (to->handles != NULL) g_free (to->handles);
+  g_clear_pointer (&to->handles, g_free);
   if (to->num_handles > 0)
-    to->handles = g_malloc (sizeof (Handle *)*to->num_handles);
+    to->handles = g_new0 (Handle *, to->num_handles);
   else
     to->handles = NULL;
 
   to->num_connections = from->num_connections;
-  if (to->connections != NULL) g_free (to->connections);
+  g_clear_pointer (&to->connections, g_free);
   if (to->num_connections > 0)
-    to->connections = g_malloc0 (sizeof (ConnectionPoint *) * to->num_connections);
+    to->connections = g_new0 (ConnectionPoint *, to->num_connections);
   else
     to->connections = NULL;
 
@@ -519,8 +515,8 @@ _object_exchange_free (ObjectChange *change)
   DiaObject *obj = c->applied ? c->orig : c->subst;
 
   if (obj) {
-    obj->ops->destroy(obj);
-    g_free(obj);
+    obj->ops->destroy (obj);
+    g_clear_pointer (&obj, g_free);
   }
 }
 
@@ -571,10 +567,10 @@ destroy_object_list (GList *list_to_be_destroyed)
   while (list != NULL) {
     obj = (DiaObject *)list->data;
 
-    obj->ops->destroy(obj);
-    g_free(obj);
+    obj->ops->destroy (obj);
+    g_clear_pointer (&obj, g_free);
 
-    list = g_list_next(list);
+    list = g_list_next (list);
   }
 
   g_list_free(list_to_be_destroyed);
@@ -1322,7 +1318,7 @@ dia_object_type_get_icon (const DiaObjectType *type)
     pixbuf = gdk_pixbuf_new_from_file (type->pixmap_file, &error);
     if (error) {
       g_warning ("%s", error->message);
-      g_error_free (error);
+      g_clear_error (&error);
     }
   } else {
     const char **pixmap_data = icon_data;
diff --git a/lib/object_defaults.c b/lib/object_defaults.c
index 073915b0..9d20d386 100644
--- a/lib/object_defaults.c
+++ b/lib/object_defaults.c
@@ -69,15 +69,18 @@ _obj_create (gpointer key,
     g_hash_table_insert(ht, obj->type->name, obj);
 }
 
+
 static void
 _obj_destroy (gpointer val)
 {
   DiaObject *obj = (DiaObject *)val;
 
   object_destroy (obj);
-  g_free (obj);
+
+  g_clear_pointer (&obj, g_free);
 }
 
+
 /**
  * dia_object_defaults_load:
  * @filename: the file to load from or NULL for default
@@ -109,7 +112,7 @@ dia_object_defaults_load (const gchar *filename, gboolean create_lazy, DiaContex
 
   /* overload properties from file */
   if (!filename) {
-    gchar *default_filename = dia_config_filename("defaults.dia");
+    char *default_filename = dia_config_filename ("defaults.dia");
 
     dia_context_set_filename (ctx, default_filename);
     if (g_file_test (default_filename, G_FILE_TEST_EXISTS)) {
@@ -117,7 +120,7 @@ dia_object_defaults_load (const gchar *filename, gboolean create_lazy, DiaContex
     } else {
       doc = NULL;
     }
-    g_free (default_filename);
+    g_clear_pointer (&default_filename, g_free);
   } else {
     dia_context_set_filename (ctx, filename);
     doc = diaXmlParseFile (filename, ctx, FALSE);
@@ -326,17 +329,16 @@ _obj_store (gpointer key,
     layer_name = g_strdup ("default");
 
   li = g_hash_table_lookup (ri->layer_hash, layer_name);
-  if (!li)
-    {
-      li = g_new (MyLayerInfo, 1);
-      li->node = xmlNewChild(ri->node, ri->name_space, (const xmlChar *)"layer", NULL);
-      xmlSetProp(li->node, (const xmlChar *)"name", (xmlChar *)layer_name);
-      xmlSetProp(li->node, (const xmlChar *)"visible", (const xmlChar *)"false");
-      li->pos.x = li->pos.y = 0.0;
-      g_hash_table_insert (ri->layer_hash, layer_name, li);
-    }
-  else
-    g_free (layer_name);
+  if (!li) {
+    li = g_new0 (MyLayerInfo, 1);
+    li->node = xmlNewChild(ri->node, ri->name_space, (const xmlChar *)"layer", NULL);
+    xmlSetProp(li->node, (const xmlChar *)"name", (xmlChar *)layer_name);
+    xmlSetProp(li->node, (const xmlChar *)"visible", (const xmlChar *)"false");
+    li->pos.x = li->pos.y = 0.0;
+    g_hash_table_insert (ri->layer_hash, layer_name, li);
+  } else {
+    g_clear_pointer (&layer_name, g_free);
+  }
 
   obj_node = xmlNewChild(li->node, NULL, (const xmlChar *)"object", NULL);
   xmlSetProp(obj_node, (const xmlChar *)"type", (xmlChar *) obj->type->name);
@@ -401,8 +403,8 @@ dia_object_defaults_save (const gchar *filename, DiaContext *ctx)
   g_hash_table_foreach (defaults_hash, _obj_store, &ni);
 
   ret = xmlDiaSaveFile (real_filename, doc);
-  g_free (real_filename);
-  xmlFreeDoc(doc);
+  g_clear_pointer (&real_filename, g_free);
+  xmlFreeDoc (doc);
 
   g_hash_table_destroy (ni.layer_hash);
 
diff --git a/lib/orth_conn.c b/lib/orth_conn.c
index c0fcf0d9..fbb43727 100644
--- a/lib/orth_conn.c
+++ b/lib/orth_conn.c
@@ -344,7 +344,7 @@ adjust_handle_count_to(OrthConn *orth, gint count) {
     for (i=count-1; i<orth->numhandles-1; i++) {
       Handle *handle = orth->handles[i];
       object_remove_handle(&orth->object,handle);
-      g_free(handle);
+      g_clear_pointer (&handle, g_free);
       orth->handles[i] = NULL;
     }
     orth->handles[count-1] = orth->handles[orth->numhandles-1];
@@ -406,7 +406,7 @@ orthconn_update_data(OrthConn *orth)
             new_points[orth->numpoints-1].x, new_points[orth->numpoints-1].y);
       */
     }
-    g_free(points);
+    g_clear_pointer (&points, g_free);
     orth->points = new_points;
   }
 
@@ -549,9 +549,7 @@ orthconn_set_points (OrthConn *orth, int num_points, Point *points)
 
   orth->numpoints = num_points;
 
-  if (orth->points) {
-    g_free (orth->points);
-  }
+  g_clear_pointer (&orth->points, g_free);
 
   orth->points = g_new0 (Point, orth->numpoints);
 
@@ -562,7 +560,7 @@ orthconn_set_points (OrthConn *orth, int num_points, Point *points)
   /* Set up the orientation array. */
   /* Maybe we could get rid of this array altogether? */
   orth->numorient = orth->numpoints-1;
-  if (orth->orientation) g_free(orth->orientation);
+  g_clear_pointer (&orth->orientation, g_free);
   orth->orientation = g_new(Orientation, orth->numorient);
   horiz = (fabs(orth->points[0].y-orth->points[1].y) < 0.00001);
   for (i = 0; i < orth->numorient; i++) {
@@ -619,13 +617,13 @@ orthconn_destroy(OrthConn *orth)
   connpointline_destroy(orth->midpoints);
   object_destroy(&orth->object);
 
-  g_free(orth->points);
-  g_free(orth->orientation);
+  g_clear_pointer (&orth->points, g_free);
+  g_clear_pointer (&orth->orientation, g_free);
 
   for (i=0;i<orth->numpoints-1;i++)
-    g_free(orth->handles[i]);
+    g_clear_pointer (&orth->handles[i], g_free);
 
-  g_free(orth->handles);
+  g_clear_pointer (&orth->handles, g_free);
 }
 
 static void
@@ -953,17 +951,13 @@ endsegment_change_free (struct EndSegmentChange *change)
 {
   if ( (change->type==TYPE_ADD_SEGMENT && !change->applied) ||
        (change->type==TYPE_REMOVE_SEGMENT && change->applied) ){
-    if (change->handle) {
-      g_free (change->handle);
-    }
-    change->handle = NULL;
+    g_clear_pointer (&change->handle, g_free);
   }
   if (change->cplchange) {
     if (change->cplchange->free) {
       change->cplchange->free (change->cplchange);
     }
-    g_free (change->cplchange);
-    change->cplchange = NULL;
+    g_clear_pointer (&change->cplchange, g_free);
   }
 }
 
@@ -1107,25 +1101,20 @@ midsegment_change_free(struct MidSegmentChange *change)
 {
   if ( (change->type==TYPE_ADD_SEGMENT && !change->applied) ||
        (change->type==TYPE_REMOVE_SEGMENT && change->applied) ){
-    if (change->handles[0])
-      g_free(change->handles[0]);
-    change->handles[0] = NULL;
-    if (change->handles[1])
-      g_free(change->handles[1]);
-    change->handles[1] = NULL;
+    g_clear_pointer (&change->handles[0], g_free);
+    g_clear_pointer (&change->handles[1], g_free);
   }
 
   if (change->cplchange[0]) {
     if (change->cplchange[0]->free)
       change->cplchange[0]->free(change->cplchange[0]);
-    g_free(change->cplchange[0]);
-    change->cplchange[0] = NULL;
+    g_clear_pointer (&change->cplchange[0], g_free);
   }
+
   if (change->cplchange[1]) {
     if (change->cplchange[1]->free)
       change->cplchange[1]->free(change->cplchange[1]);
-    g_free(change->cplchange[1]);
-    change->cplchange[1] = NULL;
+    g_clear_pointer (&change->cplchange[1], g_free);
   }
 }
 
@@ -1239,7 +1228,7 @@ midsegment_create_change(OrthConn *orth, enum change_type type,
 static void
 autoroute_change_free(struct AutorouteChange *change)
 {
-  g_free(change->points);
+  g_clear_pointer (&change->points, g_free);
 }
 
 static void
diff --git a/lib/parent.c b/lib/parent.c
index daa4f0ae..d11073b1 100644
--- a/lib/parent.c
+++ b/lib/parent.c
@@ -212,15 +212,19 @@ gboolean parent_handle_move_in_check(DiaObject *object, Point *to, Point *start_
       If delta is not present, these are the extents *before* any moves
       If delta is present, delta is considered into the extents's position
       */
-Point parent_move_child_delta (DiaRectangle *p_ext, DiaRectangle *c_ext, Point *delta)
+Point
+parent_move_child_delta (DiaRectangle *p_ext,
+                         DiaRectangle *c_ext,
+                         Point        *delta)
 {
-    Point new_delta = {0, 0};
-    gboolean free_delta = FALSE;
-    if (delta == NULL)
-    {
-      delta = g_new0(Point, 1);
-      free_delta = TRUE;
-    }
+  Point new_delta = { 0, 0 };
+  gboolean free_delta = FALSE;
+
+  if (delta == NULL) {
+    delta = g_new0 (Point, 1);
+    free_delta = TRUE;
+  }
+
     /* we check if the child extent would be inside the parent extent after the move
       if not, we calculate how far we have to move the extent back to place it back
       inside the parent extent */
@@ -234,10 +238,11 @@ Point parent_move_child_delta (DiaRectangle *p_ext, DiaRectangle *c_ext, Point *
     else if (c_ext->top + delta->y + (c_ext->bottom - c_ext->top) > p_ext->bottom)
       new_delta.y = p_ext->bottom  - (c_ext->top + delta->y + (c_ext->bottom - c_ext->top));
 
-    if (free_delta)
-      g_free(delta);
+  if (free_delta) {
+    g_clear_pointer (&delta, g_free);
+  }
 
-    return new_delta;
+  return new_delta;
 }
 
 /* the caller must free the returned rectangle */
diff --git a/lib/persistence.c b/lib/persistence.c
index 5d1e9dd1..e0c7f86c 100644
--- a/lib/persistence.c
+++ b/lib/persistence.c
@@ -153,7 +153,7 @@ persistence_load_list(gchar *role, xmlNodePtr node, DiaContext *ctx)
     /* This frees the strings, too? */
     g_strfreev(strings);
     /* yes but not the other one --hb */
-    g_free (string);
+    g_clear_pointer (&string, g_free);
     plist = g_new(PersistentList, 1);
     plist->glist = list;
     plist->role = role;
@@ -331,7 +331,7 @@ persistence_load (void)
   persistence_init ();
 
   if (!g_file_test (filename, G_FILE_TEST_IS_REGULAR)) {
-    g_free (filename);
+    g_clear_pointer (&filename, g_free);
     return;
   }
   ctx = dia_context_new (_("Persistence"));
@@ -350,7 +350,7 @@ persistence_load (void)
     }
     xmlFreeDoc (doc);
   }
-  g_free (filename);
+  g_clear_pointer (&filename, g_free);
   dia_context_release (ctx);
 }
 
@@ -522,7 +522,7 @@ persistence_save (void)
   persistence_save_type (doc, ctx, persistent_colors, persistence_save_color);
 
   xmlDiaSaveFile (filename, doc);
-  g_free (filename);
+  g_clear_pointer (&filename, g_free);
   xmlFreeDoc (doc);
   dia_context_release (ctx);
 }
@@ -579,20 +579,15 @@ persistence_update_window(GtkWindow *window, gboolean isclosed)
   wininfo = (PersistentWindow *)g_hash_table_lookup(persistent_windows, name);
 
   if (wininfo != NULL) {
-    persistence_store_window_info(window, wininfo, isclosed);
+    persistence_store_window_info (window, wininfo, isclosed);
   } else {
-    wininfo = g_new0(PersistentWindow, 1);
-    persistence_store_window_info(window, wininfo, FALSE);
-    g_hash_table_insert(persistent_windows, (gchar *)name, wininfo);
-  }
-  if (wininfo->window != NULL && wininfo->window != window) {
-    g_object_unref(wininfo->window);
-    wininfo->window = NULL;
-  }
-  if (wininfo->window == NULL) {
-    wininfo->window = window;
-    g_object_ref(window);
+    wininfo = g_new0 (PersistentWindow, 1);
+    persistence_store_window_info (window, wininfo, FALSE);
+    g_hash_table_insert (persistent_windows, (char *) name, wininfo);
   }
+
+  g_set_object (&wininfo->window, window);
+
   /* catch the transistion */
   wininfo->isopen = !isclosed;
 }
@@ -650,7 +645,7 @@ persistence_window_unmap (GtkWindow *window,
                           GdkEvent  *event,
                           gpointer   data)
 {
-  g_return_val_if_fail (event->type != GDK_UNMAP, FALSE);
+  g_return_val_if_fail (event->type == GDK_UNMAP, FALSE);
 
   dia_log_message ("unmap (%s)", persistence_get_window_name (window));
 
@@ -757,15 +752,7 @@ persistence_register_window (GtkWindow *window)
     g_hash_table_insert (persistent_windows, (gchar *) name, wininfo);
   }
 
-  if (wininfo->window != NULL && wininfo->window != window) {
-    g_object_unref (wininfo->window);
-    wininfo->window = NULL;
-  }
-
-  if (wininfo->window == NULL) {
-    wininfo->window = window;
-    g_object_ref (window);
-  }
+  g_set_object (&wininfo->window, window);
 
   g_signal_connect (G_OBJECT (window), "configure-event",
                     G_CALLBACK (persistence_window_configure), NULL);
@@ -973,7 +960,7 @@ persistent_list_add(const gchar *role, const gchar *item)
        * selecting a file there several times.  Yes, it should be strdup'd,
        * but it isn't.
        */
-      /*g_free(old_elem->data);*/
+      /*g_clear_pointer (&old_elem->data, g_free);*/
       g_list_free_1(old_elem);
       old_elem = g_list_find_custom(tmplist, item, (GCompareFunc)g_ascii_strcasecmp);
       existed = TRUE;
@@ -1007,9 +994,11 @@ persistent_list_remove(const gchar *role, const gchar *item)
   GList *entry = g_list_find_custom(plist->glist, item, (GCompareFunc)g_ascii_strcasecmp);
   if (entry != NULL) {
     plist->glist = g_list_remove_link(plist->glist, entry);
-    g_free(entry->data);
+    g_clear_pointer (&entry->data, g_free);
     return TRUE;
-  } else return FALSE;
+  } else {
+    return FALSE;
+  }
 }
 
 void
diff --git a/lib/plug-ins.c b/lib/plug-ins.c
index 7fd554a7..a7fb65e5 100644
--- a/lib/plug-ins.c
+++ b/lib/plug-ins.c
@@ -79,9 +79,9 @@ dia_plugin_info_init(PluginInfo *info,
                     PluginCanUnloadFunc can_unload_func,
                     PluginUnloadFunc unload_func)
 {
-  g_free(info->name);
+  g_clear_pointer (&info->name, g_free);
   info->name = g_strdup(name);
-  g_free(info->description);
+  g_clear_pointer (&info->description, g_free);
   info->description = g_strdup(description);
   info->can_unload_func = can_unload_func;
   info->unload_func = unload_func;
@@ -297,10 +297,10 @@ for_each_in_dir(const gchar *directory, ForEachInDirDoFunc dofunc,
   if (g_stat(directory, &statbuf) < 0)
     return;
 
-  dp = g_dir_open(directory, 0, &error);
+  dp = g_dir_open (directory, 0, &error);
   if (dp == NULL) {
-    g_warning("Could not open `%s'\n`%s'", directory, error->message);
-    g_error_free (error);
+    g_warning ("Could not open `%s'\n`%s'", directory, error->message);
+    g_clear_error (&error);
     return;
   }
 
@@ -308,7 +308,7 @@ for_each_in_dir(const gchar *directory, ForEachInDirDoFunc dofunc,
     gchar *name = g_build_filename(directory,dentry,NULL);
 
     if (filter(name)) dofunc(name);
-    g_free(name);
+    g_clear_pointer (&name, g_free);
   }
   g_dir_close(dp);
 }
@@ -338,16 +338,16 @@ dia_register_plugins_in_dir(const gchar *directory)
 void
 dia_register_plugins(void)
 {
-  const gchar *library_path;
-  const gchar *lib_dir;
+  const char *library_path;
+  char *lib_dir;
 
-  library_path = g_getenv("DIA_LIB_PATH");
+  library_path = g_getenv ("DIA_LIB_PATH");
 
-  lib_dir = dia_config_filename("objects");
+  lib_dir = dia_config_filename ("objects");
 
   if (lib_dir != NULL) {
-    dia_register_plugins_in_dir(lib_dir);
-    g_free((char *)lib_dir);
+    dia_register_plugins_in_dir (lib_dir);
+    g_clear_pointer (&lib_dir, g_free);
   }
 
   if (library_path != NULL) {
@@ -359,13 +359,13 @@ dia_register_plugins(void)
     }
     g_strfreev(paths);
   } else {
-    library_path = dia_get_lib_directory();
+    lib_dir = dia_get_lib_directory ();
 
-    dia_register_plugins_in_dir(library_path);
-    g_free((char *)library_path);
+    dia_register_plugins_in_dir (lib_dir);
+    g_clear_pointer (&lib_dir, g_free);
   }
   /* FIXME: this isn't needed anymore */
-  free_pluginrc();
+  free_pluginrc ();
 }
 
 void
@@ -381,7 +381,7 @@ dia_register_builtin_plugin(PluginInitFunc init_func)
   info->init_func = init_func;
 
   if ((* init_func)(info) != DIA_PLUGIN_INIT_OK) {
-    g_free(info);
+    g_clear_pointer (&info, g_free);
     return;
   }
   plugins = g_list_prepend(plugins, info);
@@ -420,7 +420,7 @@ ensure_pluginrc(void)
   else
     pluginrc = NULL;
 
-  g_free(filename);
+  g_clear_pointer (&filename, g_free);
 
   if (!pluginrc) {
     pluginrc = xmlNewDoc((const xmlChar *)"1.0");
@@ -516,10 +516,10 @@ info_fill_from_pluginrc(PluginInfo *info)
          continue;
        content = (gchar *)xmlNodeGetContent(node2);
        if (!xmlStrcmp(node2->name, (const xmlChar *)"name")) {
-         g_free(info->name);
+         g_clear_pointer (&info->name, g_free);
          info->name = g_strdup(content);
        } else if (!xmlStrcmp(node2->name, (const xmlChar *)"description")) {
-         g_free(info->description);
+         g_clear_pointer (&info->description, g_free);
          info->description = g_strdup(content);
        }
        xmlFree(content);
@@ -586,7 +586,7 @@ dia_pluginrc_write(void)
 
   xmlDiaSaveFile(filename, pluginrc);
 
-  g_free(filename);
+  g_clear_pointer (&filename, g_free);
   free_pluginrc();
 }
 
diff --git a/lib/poly_conn.c b/lib/poly_conn.c
index 9d002555..e681351b 100644
--- a/lib/poly_conn.c
+++ b/lib/poly_conn.c
@@ -382,8 +382,7 @@ polyconn_set_points(PolyConn *poly, int num_points, Point *points)
 
   poly->numpoints = num_points;
 
-  if (poly->points)
-    g_free(poly->points);
+  g_clear_pointer (&poly->points, g_free);
 
   poly->points = g_malloc((poly->numpoints)*sizeof(Point));
 
@@ -436,11 +435,11 @@ polyconn_destroy (PolyConn *poly)
   object_destroy (&poly->object);
 
   for (i = 0; i < poly->numpoints; i++) {
-    g_free (temp_handles[i]);
+    g_clear_pointer (&temp_handles[i], g_free);
   }
-  g_free (temp_handles);
+  g_clear_pointer (&temp_handles, g_free);
 
-  g_free (poly->points);
+  g_clear_pointer (&poly->points, g_free);
 }
 
 
@@ -511,9 +510,7 @@ polyconn_change_free(struct PointChange *change)
 {
   if ( (change->type==TYPE_ADD_POINT && !change->applied) ||
        (change->type==TYPE_REMOVE_POINT && change->applied) ){
-    if (change->handle)
-      g_free(change->handle);
-    change->handle = NULL;
+    g_clear_pointer (&change->handle, g_free);
   }
 }
 
diff --git a/lib/polyshape.c b/lib/polyshape.c
index 158dc83d..2a2278a4 100644
--- a/lib/polyshape.c
+++ b/lib/polyshape.c
@@ -424,7 +424,7 @@ polyshape_set_points(PolyShape *poly, int num_points, Point *points)
 
   poly->numpoints = num_points;
 
-  if (poly->points) g_free(poly->points);
+  g_clear_pointer (&poly->points, g_free);
   poly->points = g_new(Point, num_points);
 
   for (i = 0; i < num_points; i++) {
@@ -482,16 +482,16 @@ polyshape_destroy (PolyShape *poly)
   object_destroy (&poly->object);
 
   for (i = 0; i < poly->numpoints;i++) {
-    g_free (temp_handles[i]);
+    g_clear_pointer (&temp_handles[i], g_free);
   }
-  g_free (temp_handles);
+  g_clear_pointer (&temp_handles, g_free);
 
   for (i = 0; i < NUM_CONNECTIONS (poly); i++) {
-    g_free (temp_cps[i]);
+    g_clear_pointer (&temp_cps[i], g_free);
   }
-  g_free (temp_cps);
+  g_clear_pointer (&temp_cps, g_free);
 
-  g_free (poly->points);
+  g_clear_pointer (&poly->points, g_free);
 }
 
 
@@ -555,12 +555,9 @@ polyshape_change_free(struct PointChange *change)
 {
   if ( (change->type==TYPE_ADD_POINT && !change->applied) ||
        (change->type==TYPE_REMOVE_POINT && change->applied) ){
-    g_free(change->handle);
-    g_free(change->cp1);
-    g_free(change->cp2);
-    change->handle = NULL;
-    change->cp1 = NULL;
-    change->cp2 = NULL;
+    g_clear_pointer (&change->handle, g_free);
+    g_clear_pointer (&change->cp1, g_free);
+    g_clear_pointer (&change->cp2, g_free);
   }
 }
 
diff --git a/lib/prop_attr.c b/lib/prop_attr.c
index ff7a279c..4ac03558 100644
--- a/lib/prop_attr.c
+++ b/lib/prop_attr.c
@@ -203,12 +203,12 @@ arrowprop_load(ArrowProperty *prop, AttributeNode attr, DataNode data, DiaContex
     if ((attr = object_find_attribute(obj_node, str)) &&
         (data = attribute_first_data(attr)))
       prop->arrow_data.length = data_real(data, ctx);
-    g_free(str);
+    g_clear_pointer (&str, g_free);
     str = g_strconcat(prop->common.descr->name, "_width", NULL);
     if ((attr = object_find_attribute(obj_node, str)) &&
         (data = attribute_first_data(attr)))
       prop->arrow_data.width = data_real(data, ctx);
-    g_free(str);
+    g_clear_pointer (&str, g_free);
   }
 }
 
@@ -220,11 +220,11 @@ arrowprop_save(ArrowProperty *prop, AttributeNode attr, DiaContext *ctx)
     ObjectNode obj_node = attr->parent;
     gchar *str = g_strconcat(prop->common.descr->name, "_length", NULL);
     attr = new_attribute(obj_node, str);
-    g_free(str);
+    g_clear_pointer (&str, g_free);
     data_add_real(attr, prop->arrow_data.length, ctx);
     str = g_strconcat(prop->common.descr->name, "_width", NULL);
     attr = new_attribute(obj_node, str);
-    g_free(str);
+    g_clear_pointer (&str, g_free);
     data_add_real(attr, prop->arrow_data.width, ctx);
   }
 }
@@ -377,13 +377,15 @@ fontprop_new(const PropDescription *pdesc, PropDescToPropPredicate reason)
   return prop;
 }
 
+
 static void
 fontprop_free (FontProperty *prop)
 {
   g_clear_object (&prop->font_data);
-  g_free (prop);
+  g_clear_pointer (&prop, g_free);
 }
 
+
 static FontProperty *
 fontprop_copy(FontProperty *src)
 {
diff --git a/lib/prop_basic.c b/lib/prop_basic.c
index 0dbd8b67..951a1237 100644
--- a/lib/prop_basic.c
+++ b/lib/prop_basic.c
@@ -68,11 +68,11 @@ make_new_prop(const char *name, PropertyType type, guint flags)
   if (!hash) hash = g_hash_table_new((GHashFunc)desc_hash_hash,
                                      (GCompareFunc)desc_hash_compare);
 
-  descr = g_hash_table_lookup(hash,moniker);
+  descr = g_hash_table_lookup (hash,moniker);
   if (descr) {
-    g_free(moniker);
+    g_clear_pointer (&moniker, g_free);
   } else {
-    descr = g_new0(PropDescription,1);
+    descr = g_new0 (PropDescription,1);
     descr->name = name;
     descr->type = type;
     descr->flags = flags;
@@ -237,12 +237,14 @@ noopprop_new(const PropDescription *pdesc, PropDescToPropPredicate reason)
   return prop;
 }
 
+
 void
-noopprop_free(NoopProperty *prop)
+noopprop_free (NoopProperty *prop)
 {
-  g_free(prop);
+  g_clear_pointer (&prop, g_free);
 }
 
+
 NoopProperty *
 noopprop_copy(NoopProperty *src)
 {
diff --git a/lib/prop_dict.c b/lib/prop_dict.c
index 60efddbd..df75e190 100644
--- a/lib/prop_dict.c
+++ b/lib/prop_dict.c
@@ -61,7 +61,7 @@ dictprop_free(DictProperty *prop)
 {
   if (prop->dict)
     g_hash_table_destroy(prop->dict);
-  g_free(prop);
+  g_clear_pointer (&prop, g_free);
 }
 
 static void
diff --git a/lib/prop_geomtypes.c b/lib/prop_geomtypes.c
index 746aeeb7..ded0c485 100644
--- a/lib/prop_geomtypes.c
+++ b/lib/prop_geomtypes.c
@@ -450,13 +450,15 @@ pointarrayprop_new(const PropDescription *pdesc,
   return prop;
 }
 
+
 static void
-pointarrayprop_free(PointarrayProperty *prop)
+pointarrayprop_free (PointarrayProperty *prop)
 {
-  g_array_free(prop->pointarray_data,TRUE);
-  g_free(prop);
+  g_array_free (prop->pointarray_data,TRUE);
+  g_clear_pointer (&prop, g_free);
 }
 
+
 static PointarrayProperty *
 pointarrayprop_copy(PointarrayProperty *src)
 {
@@ -506,18 +508,22 @@ pointarrayprop_get_from_offset(PointarrayProperty *prop,
       struct_member(ofs_val,i * sizeof(Point),Point);
 }
 
+
 static void
-pointarrayprop_set_from_offset(PointarrayProperty *prop,
-                               void *base, guint offset, guint offset2)
+pointarrayprop_set_from_offset (PointarrayProperty *prop,
+                                void               *base,
+                                guint               offset,
+                                guint               offset2)
 {
   guint nvals = prop->pointarray_data->len;
-  Point *vals = g_memdup(&g_array_index(prop->pointarray_data,Point,0),
-                         sizeof(Point) * nvals);
-  g_free(struct_member(base,offset,Point *));
-  struct_member(base,offset,Point *) = vals;
-  struct_member(base,offset2,guint) = nvals;
+  Point *vals = g_memdup (&g_array_index (prop->pointarray_data, Point, 0),
+                          sizeof(Point) * nvals);
+  g_clear_pointer (&struct_member (base, offset, Point *), g_free);
+  struct_member (base, offset, Point *) = vals;
+  struct_member (base, offset2, guint) = nvals;
 }
 
+
 static const PropertyOps pointarrayprop_ops = {
   (PropertyType_New) pointarrayprop_new,
   (PropertyType_Free) pointarrayprop_free,
@@ -618,7 +624,7 @@ static void
 bezpointarrayprop_free(BezPointarrayProperty *prop)
 {
   g_array_free(prop->bezpointarray_data,TRUE);
-  g_free(prop);
+  g_clear_pointer (&prop, g_free);
 }
 
 static BezPointarrayProperty *
@@ -662,32 +668,40 @@ bezpointarrayprop_save(BezPointarrayProperty *prop, AttributeNode attr, DiaConte
                       &g_array_index(prop->bezpointarray_data,BezPoint,i), ctx);
 }
 
+
 static void
-bezpointarrayprop_get_from_offset(BezPointarrayProperty *prop,
-                                  void *base, guint offset, guint offset2)
+bezpointarrayprop_get_from_offset (BezPointarrayProperty *prop,
+                                   void                  *base,
+                                   guint                  offset,
+                                   guint                  offset2)
 {
-  guint nvals = struct_member(base,offset2,guint);
+  guint nvals = struct_member (base, offset2, guint);
   guint i;
-  void *ofs_val = struct_member(base,offset,void *);
-  g_array_set_size(prop->bezpointarray_data,nvals);
-  for (i = 0; i < nvals; i++)
-    g_array_index(prop->bezpointarray_data,BezPoint,i) =
-      struct_member(ofs_val,i * sizeof(BezPoint),BezPoint);
+  void *ofs_val = struct_member (base, offset, void *);
+  g_array_set_size (prop->bezpointarray_data, nvals);
+  for (i = 0; i < nvals; i++) {
+    g_array_index (prop->bezpointarray_data, BezPoint, i) =
+      struct_member (ofs_val, i * sizeof (BezPoint), BezPoint);
+  }
 }
 
+
 static void
 bezpointarrayprop_set_from_offset(BezPointarrayProperty *prop,
-                                  void *base, guint offset, guint offset2)
+                                  void                  *base,
+                                  guint                  offset,
+                                  guint                  offset2)
 {
   guint nvals = prop->bezpointarray_data->len;
-  BezPoint *vals = g_memdup(&g_array_index(prop->bezpointarray_data,
-                                           BezPoint,0),
-                            sizeof(BezPoint) * nvals);
-  g_free(struct_member(base,offset,gint *));
-  struct_member(base,offset,BezPoint *) = vals;
-  struct_member(base,offset2,guint) = nvals;
+  BezPoint *vals = g_memdup (&g_array_index (prop->bezpointarray_data,
+                                             BezPoint, 0),
+                             sizeof (BezPoint) * nvals);
+  g_clear_pointer (&struct_member (base, offset, int *), g_free);
+  struct_member (base, offset, BezPoint *) = vals;
+  struct_member (base, offset2, guint) = nvals;
 }
 
+
 static const PropertyOps bezpointarrayprop_ops = {
   (PropertyType_New) bezpointarrayprop_new,
   (PropertyType_Free) bezpointarrayprop_free,
diff --git a/lib/prop_inttypes.c b/lib/prop_inttypes.c
index 1bf1eee9..095baf53 100644
--- a/lib/prop_inttypes.c
+++ b/lib/prop_inttypes.c
@@ -80,7 +80,7 @@ charprop_set_from_widget(CharProperty *prop, WIDGET *widget)
 {
   gchar *buf = gtk_editable_get_chars(GTK_EDITABLE(widget), 0, 1);
   prop->char_data = g_utf8_get_char(buf);
-  g_free(buf);
+  g_clear_pointer (&buf, g_free);
 }
 
 static void
@@ -90,7 +90,7 @@ charprop_load(CharProperty *prop, AttributeNode attr, DataNode data, DiaContext
 
   if (str && str[0]) {
     prop->char_data = g_utf8_get_char(str);
-    g_free(str);
+    g_clear_pointer (&str, g_free);
   } else {
     g_warning("Could not read character data for attribute %s",
               prop->common.descr->name);
@@ -378,7 +378,7 @@ static void
 intarrayprop_free(IntarrayProperty *prop)
 {
   g_array_free(prop->intarray_data,TRUE);
-  g_free(prop);
+  g_clear_pointer (&prop, g_free);
 }
 
 static IntarrayProperty *
@@ -417,31 +417,39 @@ intarrayprop_save(IntarrayProperty *prop, AttributeNode attr, DiaContext *ctx)
     data_add_int(attr, g_array_index(prop->intarray_data,gint,i), ctx);
 }
 
+
 static void
-intarrayprop_get_from_offset(IntarrayProperty *prop,
-                             void *base, guint offset, guint offset2)
+intarrayprop_get_from_offset (IntarrayProperty *prop,
+                              void             *base,
+                              guint             offset,
+                              guint             offset2)
 {
-  guint nvals = struct_member(base,offset2,guint);
+  guint nvals = struct_member (base, offset2, guint);
   guint i;
-  void *ofs_val = struct_member(base,offset,void *);
-  g_array_set_size(prop->intarray_data,nvals);
-  for (i = 0; i < nvals; i++)
-    g_array_index(prop->intarray_data,gint,i) =
-      struct_member(ofs_val,i * sizeof(gint),gint);
+  void *ofs_val = struct_member(base, offset, void *);
+  g_array_set_size(prop->intarray_data, nvals);
+  for (i = 0; i < nvals; i++) {
+    g_array_index (prop->intarray_data, int, i) =
+      struct_member (ofs_val, i * sizeof (int), int);
+  }
 }
 
+
 static void
-intarrayprop_set_from_offset(IntarrayProperty *prop,
-                             void *base, guint offset, guint offset2)
+intarrayprop_set_from_offset (IntarrayProperty *prop,
+                              void             *base,
+                              guint             offset,
+                              guint             offset2)
 {
   guint nvals = prop->intarray_data->len;
-  gint *vals = g_memdup(&g_array_index(prop->intarray_data,gint,0),
-                        sizeof(gint) * nvals);
-  g_free(struct_member(base,offset,gint *));
-  struct_member(base,offset,gint *) = vals;
-  struct_member(base,offset2,guint) = nvals;
+  int *vals = g_memdup (&g_array_index (prop->intarray_data, int, 0),
+                        sizeof (int) * nvals);
+  g_clear_pointer (&struct_member (base, offset, int *), g_free);
+  struct_member (base, offset, int *) = vals;
+  struct_member (base, offset2, guint) = nvals;
 }
 
+
 static const PropertyOps intarrayprop_ops = {
   (PropertyType_New) intarrayprop_new,
   (PropertyType_Free) intarrayprop_free,
@@ -629,7 +637,7 @@ static void
 enumarrayprop_free(EnumarrayProperty *prop)
 {
   g_array_free(prop->enumarray_data,TRUE);
-  g_free(prop);
+  g_clear_pointer (&prop, g_free);
 }
 
 static EnumarrayProperty *
@@ -669,31 +677,39 @@ enumarrayprop_save(EnumarrayProperty *prop, AttributeNode attr, DiaContext *ctx)
     data_add_enum(attr, g_array_index(prop->enumarray_data,gint,i), ctx);
 }
 
+
 static void
-enumarrayprop_get_from_offset(EnumarrayProperty *prop,
-                              void *base, guint offset, guint offset2)
+enumarrayprop_get_from_offset (EnumarrayProperty *prop,
+                               void              *base,
+                               guint              offset,
+                               guint              offset2)
 {
-  guint nvals = struct_member(base,offset2,guint);
+  guint nvals = struct_member (base, offset2, guint);
   guint i;
-  void *ofs_val = struct_member(base,offset,void *);
-  g_array_set_size(prop->enumarray_data,nvals);
-  for (i = 0; i < nvals; i++)
-    g_array_index(prop->enumarray_data,gint,i) =
-      struct_member(ofs_val,i * sizeof(gint),gint);
+  void *ofs_val = struct_member (base, offset, void *);
+  g_array_set_size (prop->enumarray_data, nvals);
+  for (i = 0; i < nvals; i++) {
+    g_array_index (prop->enumarray_data, int, i) =
+      struct_member(ofs_val, i * sizeof (int), int);
+  }
 }
 
+
 static void
-enumarrayprop_set_from_offset(EnumarrayProperty *prop,
-                              void *base, guint offset, guint offset2)
+enumarrayprop_set_from_offset (EnumarrayProperty *prop,
+                               void              *base,
+                               guint              offset,
+                               guint              offset2)
 {
   guint nvals = prop->enumarray_data->len;
-  gint *vals = g_memdup(&g_array_index(prop->enumarray_data,gint,0),
-                        sizeof(gint) * nvals);
-  g_free(struct_member(base,offset,gint *));
-  struct_member(base,offset,gint *) = vals;
-  struct_member(base,offset2,guint) = nvals;
+  int *vals = g_memdup (&g_array_index (prop->enumarray_data, int, 0),
+                        sizeof (int) * nvals);
+  g_clear_pointer (&struct_member (base, offset, int *), g_free);
+  struct_member (base, offset, int *) = vals;
+  struct_member (base, offset2, guint) = nvals;
 }
 
+
 static const PropertyOps enumarrayprop_ops = {
   (PropertyType_New) enumarrayprop_new,
   (PropertyType_Free) enumarrayprop_free,
diff --git a/lib/prop_matrix.c b/lib/prop_matrix.c
index 3147d3a1..1f1cb0bf 100644
--- a/lib/prop_matrix.c
+++ b/lib/prop_matrix.c
@@ -47,8 +47,8 @@ matrixprop_new(const PropDescription *pdesc, PropDescToPropPredicate reason)
 static void
 matrixprop_free(MatrixProperty *prop)
 {
-  g_free (prop->matrix);
-  g_free(prop);
+  g_clear_pointer (&prop->matrix, g_free);
+  g_clear_pointer (&prop, g_free);
 }
 
 static MatrixProperty *
@@ -93,7 +93,7 @@ data_matrix (DataNode data)
   if (matrix->xx == 1.0 && matrix->yx == 0.0 &&
       matrix->xy == 0.0 && matrix->yy == 1.0 &&
       matrix->x0 == 0.0 && matrix->y0 == 0.0) {
-    g_free (matrix);
+    g_clear_pointer (&matrix, g_free);
     return NULL;
   }
   /* TODO: check it's invertible? */
@@ -154,8 +154,8 @@ matrixprop_set_from_offset(MatrixProperty *prop,
                            void *base, guint offset, guint offset2)
 {
   DiaMatrix *dest = struct_member(base,offset,DiaMatrix *);
-  if (dest)
-    g_free (dest);
+
+  g_clear_pointer (&dest, g_free);
 
   struct_member(base,offset, DiaMatrix *) = g_memdup (prop->matrix, sizeof (DiaMatrix));
 }
@@ -254,8 +254,7 @@ matrixprop_set_from_widget(MatrixProperty *prop, GtkWidget *widget)
     }
     dia_matrix_set_angle_and_scales (prop->matrix, -angle/180.0*G_PI, sx, sy);
   } else {
-    g_free (prop->matrix);
-    prop->matrix = NULL;
+    g_clear_pointer (&prop->matrix, g_free);
   }
 }
 
diff --git a/lib/prop_pattern.c b/lib/prop_pattern.c
index 93273f9e..467b7b4f 100644
--- a/lib/prop_pattern.c
+++ b/lib/prop_pattern.c
@@ -45,18 +45,19 @@ patternprop_new(const PropDescription *pdesc, PropDescToPropPredicate reason)
   return prop;
 }
 
+
 static void
-patternprop_free(PatternProperty *prop) 
+patternprop_free (PatternProperty *prop)
 {
-  if (prop->pattern)
-    g_object_unref (prop->pattern);
-  g_free(prop);
-} 
+  g_clear_object (&prop->pattern);
+  g_free (prop);
+}
+
 
 static PatternProperty *
-patternprop_copy(PatternProperty *src) 
+patternprop_copy(PatternProperty *src)
 {
-  PatternProperty *prop = 
+  PatternProperty *prop =
     (PatternProperty *)src->common.ops->new_prop(src->common.descr,
                                               src->common.reason);
   if (src->pattern) /* TODO: rethink on edit - ...copy() ? */
@@ -116,11 +117,11 @@ data_pattern (DataNode node, DiaContext *ctx)
        dia_pattern_add_color (pattern, offset, &color);
       }
     }
-  } 
+  }
   return pattern;
 }
 
-static void 
+static void
 patternprop_load(PatternProperty *prop, AttributeNode attr, DataNode data, DiaContext *ctx)
 {
   prop->pattern = data_pattern (data, ctx);
@@ -172,17 +173,17 @@ data_add_pattern (AttributeNode attr, DiaPattern *pattern, DiaContext *ctx)
   dia_pattern_foreach (pattern, _data_add_stop, &ud);
 }
 
-static void 
-patternprop_save(PatternProperty *prop, AttributeNode attr, DiaContext *ctx) 
+static void
+patternprop_save(PatternProperty *prop, AttributeNode attr, DiaContext *ctx)
 {
   if (prop->pattern) {
     data_add_pattern (attr, prop->pattern, ctx);
   }
 }
 
-static void 
+static void
 patternprop_get_from_offset(PatternProperty *prop,
-                         void *base, guint offset, guint offset2) 
+                         void *base, guint offset, guint offset2)
 {
   /* before we start editing a simple reference should be enough */
   DiaPattern *pattern = struct_member(base,offset,DiaPattern *);
@@ -193,22 +194,28 @@ patternprop_get_from_offset(PatternProperty *prop,
     prop->pattern = NULL;
 }
 
-static void 
-patternprop_set_from_offset(PatternProperty *prop,
-                           void *base, guint offset, guint offset2)
+
+static void
+patternprop_set_from_offset (PatternProperty *prop,
+                             void            *base,
+                             guint            offset,
+                             guint            offset2)
 {
-  DiaPattern *dest = struct_member(base,offset,DiaPattern *);
-  if (dest)
-    g_object_unref (dest);
-  if (prop->pattern)
-    struct_member(base,offset, DiaPattern *) = g_object_ref (prop->pattern);
-  else
-    struct_member(base,offset, DiaPattern *) = NULL;
+  DiaPattern *dest = struct_member (base, offset, DiaPattern *);
+
+  g_clear_object (&dest);
+
+  if (prop->pattern) {
+    struct_member (base, offset, DiaPattern *) = g_object_ref (prop->pattern);
+  } else {
+    struct_member (base, offset, DiaPattern *) = NULL;
+  }
 }
 
+
 static GtkWidget *
-patternprop_get_widget (PatternProperty *prop, PropDialog *dialog) 
-{ 
+patternprop_get_widget (PatternProperty *prop, PropDialog *dialog)
+{
   GtkWidget *ret = dia_pattern_selector_new ();
   prophandler_connect(&prop->common, G_OBJECT(ret), "value_changed");
   return ret;
@@ -220,16 +227,16 @@ patternprop_reset_widget(PatternProperty *prop, GtkWidget *widget)
   dia_pattern_selector_set_pattern (widget, prop->pattern);
 }
 
+
 static void
-patternprop_set_from_widget(PatternProperty *prop, GtkWidget *widget) 
+patternprop_set_from_widget (PatternProperty *prop, GtkWidget *widget)
 {
   DiaPattern *pat = dia_pattern_selector_get_pattern (widget);
 
-  if (prop->pattern)
-    g_object_unref (prop->pattern);
-  prop->pattern = pat;
+  g_set_object (&prop->pattern, pat);
 }
 
+
 static const PropertyOps patternprop_ops = {
   (PropertyType_New) patternprop_new,
   (PropertyType_Free) patternprop_free,
@@ -245,7 +252,7 @@ static const PropertyOps patternprop_ops = {
   (PropertyType_SetFromOffset) patternprop_set_from_offset
 };
 
-void 
+void
 prop_patterntypes_register(void)
 {
   prop_type_register(PROP_TYPE_PATTERN, &patternprop_ops);
diff --git a/lib/prop_pixbuf.c b/lib/prop_pixbuf.c
index a7591615..301c58fa 100644
--- a/lib/prop_pixbuf.c
+++ b/lib/prop_pixbuf.c
@@ -43,18 +43,19 @@ pixbufprop_new(const PropDescription *pdesc, PropDescToPropPredicate reason)
   return prop;
 }
 
+
 static void
-pixbufprop_free(PixbufProperty *prop) 
+pixbufprop_free(PixbufProperty *prop)
 {
-  if (prop->pixbuf)
-    g_object_unref(prop->pixbuf);
-  g_free(prop);
-} 
+  g_clear_object (&prop->pixbuf);
+  g_clear_pointer (&prop, g_free);
+}
+
 
 static PixbufProperty *
-pixbufprop_copy(PixbufProperty *src) 
+pixbufprop_copy(PixbufProperty *src)
 {
-  PixbufProperty *prop = 
+  PixbufProperty *prop =
     (PixbufProperty *)src->common.ops->new_prop(src->common.descr,
                                               src->common.reason);
   if (src->pixbuf) /* TODO: rething on edit - gdk_pixbuf_copy() ? */
@@ -82,7 +83,7 @@ pixbuf_decode_base64 (const gchar *b64)
     guchar buf[BUF_SIZE];
     gchar *in = (gchar *)b64; /* direct access, not involving another xmlStrDup/xmlFree */
     gssize len = strlen (b64);
-       
+
     do {
       gsize step = g_base64_decode_step (in,
                                         len > BUF_SIZE ? BUF_SIZE : len,
@@ -93,6 +94,7 @@ pixbuf_decode_base64 (const gchar *b64)
       in += BUF_SIZE;
       len -= BUF_SIZE;
     } while (len > 0);
+
     if (gdk_pixbuf_loader_close (loader, error ? NULL : &error)) {
       GdkPixbufFormat *format = gdk_pixbuf_loader_get_format (loader);
       gchar  *format_name = gdk_pixbuf_format_get_name (format);
@@ -102,16 +104,16 @@ pixbuf_decode_base64 (const gchar *b64)
       pixbuf = g_object_ref (gdk_pixbuf_loader_get_pixbuf (loader));
       /* attach the mime-type to the pixbuf */
       g_object_set_data_full (G_OBJECT (pixbuf), "mime-type",
-                             g_strdup (mime_types[0]),
-                             (GDestroyNotify)g_free);
+                              g_strdup (mime_types[0]),
+                              (GDestroyNotify) g_free);
       g_strfreev (mime_types);
-      g_free (format_name);
+      g_clear_pointer (&format_name, g_free);
     } else {
       message_warning (_("Failed to load image form diagram:\n%s"), error->message);
-      g_error_free (error);
+      g_clear_error (&error);
     }
 
-    g_object_unref (loader);
+    g_clear_object (&loader);
   }
   return pixbuf;
 # undef BUF_SIZE
@@ -151,20 +153,21 @@ data_pixbuf (DataNode data, DiaContext *ctx)
       in += BUF_SIZE;
       len -= BUF_SIZE;
     } while (len > 0);
+
     if (gdk_pixbuf_loader_close (loader, error ? NULL : &error)) {
       pixbuf = g_object_ref (gdk_pixbuf_loader_get_pixbuf (loader));
     } else {
       message_warning (_("Failed to load image form diagram:\n%s"), error->message);
-      g_error_free (error);
+      g_clear_error (&error);
     }
 
-    g_object_unref (loader);
+    g_clear_object (&loader);
   }
 #  undef BUF_SIZE
   return pixbuf;
 }
 
-static void 
+static void
 pixbufprop_load(PixbufProperty *prop, AttributeNode attr, DataNode data, DiaContext *ctx)
 {
   prop->pixbuf = data_pixbuf (data, ctx);
@@ -172,7 +175,7 @@ pixbufprop_load(PixbufProperty *prop, AttributeNode attr, DataNode data, DiaCont
 
 typedef struct _EncodeData {
   GByteArray *array;
-  
+
   gsize size;
 
   gint state;
@@ -190,7 +193,7 @@ _pixbuf_encode (const gchar *buf,
 
   g_byte_array_set_size (ed->array, ed->size + growth);
   out = (gchar *)&ed->array->data[ed->size];
-  ed->size += g_base64_encode_step ((guchar *)buf, count, TRUE, 
+  ed->size += g_base64_encode_step ((guchar *)buf, count, TRUE,
                                     out, &ed->state, &ed->save);
 
   return TRUE;
@@ -220,11 +223,13 @@ pixbuf_encode_base64 (const GdkPixbuf *pixbuf, const char *prefix)
     ed.size = strlen (prefix);
     g_byte_array_append (ed.array, (guint8 *)prefix, ed.size);
   }
+
   if (!gdk_pixbuf_save_to_callback ((GdkPixbuf *)pixbuf, _pixbuf_encode, &ed, type, &error, NULL)) {
     message_error (_("Saving inline pixbuf failed:\n%s"), error->message);
-    g_error_free (error);
+    g_clear_error (&error);
     return NULL;
   }
+
   /* g_base64_encode_close ... [needs] up to 5 bytes if line-breaking is enabled */
   /* also make the array 0-terminated */
   g_byte_array_append (ed.array, (guint8 *)"\0\0\0\0\0", 6);
@@ -246,20 +251,20 @@ data_add_pixbuf (AttributeNode attr, GdkPixbuf *pixbuf, DiaContext *ctx)
   if (b64)
     (void)xmlNewChild (comp_attr, NULL, (const xmlChar *)"data", (xmlChar *)b64);
 
-  g_free (b64);
+  g_clear_pointer (&b64, g_free);
 }
 
-static void 
-pixbufprop_save(PixbufProperty *prop, AttributeNode attr, DiaContext *ctx) 
+static void
+pixbufprop_save(PixbufProperty *prop, AttributeNode attr, DiaContext *ctx)
 {
   if (prop->pixbuf) {
     data_add_pixbuf (attr, prop->pixbuf, ctx);
   }
 }
 
-static void 
+static void
 pixbufprop_get_from_offset(PixbufProperty *prop,
-                         void *base, guint offset, guint offset2) 
+                         void *base, guint offset, guint offset2)
 {
   /* before we start editing a simple reference should be enough */
   GdkPixbuf *pixbuf = struct_member(base,offset,GdkPixbuf *);
@@ -270,22 +275,30 @@ pixbufprop_get_from_offset(PixbufProperty *prop,
     prop->pixbuf = NULL;
 }
 
-static void 
-pixbufprop_set_from_offset(PixbufProperty *prop,
-                           void *base, guint offset, guint offset2)
+
+static void
+pixbufprop_set_from_offset (PixbufProperty *prop,
+                            void           *base,
+                            guint           offset,
+                            guint           offset2)
 {
-  GdkPixbuf *dest = struct_member(base,offset,GdkPixbuf *);
-  if (dest == prop->pixbuf)
+  GdkPixbuf *dest = struct_member (base, offset, GdkPixbuf *);
+
+  if (dest == prop->pixbuf) {
     return;
-  if (dest)
-    g_object_unref (dest);
-  if (prop->pixbuf)
-    struct_member(base,offset, GdkPixbuf *) = g_object_ref (prop->pixbuf);
-  else
-    struct_member(base,offset, GdkPixbuf *) = NULL;
+  }
+
+  g_clear_object (&dest);
+
+  if (prop->pixbuf) {
+    struct_member (base, offset, GdkPixbuf *) = g_object_ref (prop->pixbuf);
+  } else {
+    struct_member (base, offset, GdkPixbuf *) = NULL;
+  }
 }
 
-/* GUI stuff - not yet 
+
+/* GUI stuff - not yet
    - allow to crop
    - maybe scale
  */
@@ -299,8 +312,8 @@ _pixbuf_toggled(GtkWidget *wid)
 }
 
 static GtkWidget *
-pixbufprop_get_widget (PixbufProperty *prop, PropDialog *dialog) 
-{ 
+pixbufprop_get_widget (PixbufProperty *prop, PropDialog *dialog)
+{
   GtkWidget *ret = gtk_toggle_button_new_with_label(_("No"));
   g_signal_connect(G_OBJECT(ret), "toggled",
                    G_CALLBACK (_pixbuf_toggled), NULL);
@@ -308,25 +321,26 @@ pixbufprop_get_widget (PixbufProperty *prop, PropDialog *dialog)
   return ret;
 }
 
-static void 
+static void
 pixbufprop_reset_widget(PixbufProperty *prop, GtkWidget *widget)
 {
   gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(widget),prop->pixbuf != NULL);
 }
 
-static void 
-pixbufprop_set_from_widget(PixbufProperty *prop, GtkWidget *widget) 
+
+static void
+pixbufprop_set_from_widget(PixbufProperty *prop, GtkWidget *widget)
 {
   if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(widget))) {
-    if (!prop->pixbuf)
+    if (!prop->pixbuf) {
       message_warning (_("Cant create image data from scratch!"));
+    }
   } else {
-    if (prop->pixbuf)
-      g_object_unref (prop->pixbuf);
-    prop->pixbuf = NULL;
+    g_clear_object (&prop->pixbuf);
   }
 }
 
+
 static const PropertyOps pixbufprop_ops = {
   (PropertyType_New) pixbufprop_new,
   (PropertyType_Free) pixbufprop_free,
@@ -342,7 +356,7 @@ static const PropertyOps pixbufprop_ops = {
   (PropertyType_SetFromOffset) pixbufprop_set_from_offset
 };
 
-void 
+void
 prop_pixbuftypes_register(void)
 {
   prop_type_register(PROP_TYPE_PIXBUF, &pixbufprop_ops);
diff --git a/lib/prop_sdarray.c b/lib/prop_sdarray.c
index be8c422c..389aa435 100644
--- a/lib/prop_sdarray.c
+++ b/lib/prop_sdarray.c
@@ -63,7 +63,7 @@ arrayprop_free(ArrayProperty *prop)
 {
   arrayprop_freerecords(prop);
   g_ptr_array_free(prop->records,TRUE);
-  g_free(prop);
+  g_clear_pointer (&prop, g_free);
 }
 
 static ArrayProperty *
diff --git a/lib/prop_sdarray_widget.c b/lib/prop_sdarray_widget.c
index d66532da..a1ba443d 100644
--- a/lib/prop_sdarray_widget.c
+++ b/lib/prop_sdarray_widget.c
@@ -155,7 +155,7 @@ _text_edited (GtkCellRenderer *renderer,
 
   gtk_tree_model_get (GTK_TREE_MODEL (model), &iter,
                       column, &value, -1);
-  g_free (value);
+  g_clear_pointer (&value, g_free);
   gtk_tree_store_set (GTK_TREE_STORE (model), &iter,
                       column, g_strdup (new_text), -1);
   g_object_set_data (G_OBJECT (model), "modified", GINT_TO_POINTER (1));
@@ -374,7 +374,7 @@ _update_branch (GtkTreeSelection *selection,
       gtk_tree_store_set (GTK_TREE_STORE (model), &iter, column, branch_model, -1);
     }
     gtk_tree_view_set_model (branch_view, branch_model);
-    g_object_unref (branch_model);
+    g_clear_object (&branch_model);
   } else {
     gtk_tree_view_set_model (branch_view, NULL);
   }
@@ -594,11 +594,11 @@ _write_store (GtkTreeStore *store, GtkTreeIter *parent_iter, ArrayProperty *prop
        continue;
 
       if (p->type_quark == g_quark_from_static_string (PROP_TYPE_DARRAY)) {
-       /* recurse - with own store */
-       GtkTreeStore *child_store = create_sdarray_model ((ArrayProperty *)p);
-       _write_store (child_store, NULL, (ArrayProperty *)p);
-       gtk_tree_store_set (store, &iter, i, child_store, -1);
-       g_object_unref (child_store);
+        /* recurse - with own store */
+        GtkTreeStore *child_store = create_sdarray_model ((ArrayProperty *)p);
+        _write_store (child_store, NULL, (ArrayProperty *)p);
+        gtk_tree_store_set (store, &iter, i, child_store, -1);
+        g_clear_object (&child_store);
       } else if (p->type_quark == g_quark_from_static_string (PROP_TYPE_BOOL))
        gtk_tree_store_set (store, &iter, i, ((BoolProperty *)p)->bool_data, -1);
       else if (p->type_quark == g_quark_from_static_string (PROP_TYPE_INT))
@@ -718,15 +718,16 @@ _read_store (GtkTreeStore *store, GtkTreeIter *iter, ArrayProperty *prop)
        continue;
 
       if (p->type_quark == g_quark_from_static_string (PROP_TYPE_DARRAY)) {
-       /* recurse - with own store */
-       GtkTreeStore *child_store;
-       GtkTreeIter child_iter;
-
-       gtk_tree_model_get (model, iter, i, &child_store, -1);
-       if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (child_store), &child_iter))
-         _read_store (child_store, &child_iter, (ArrayProperty *)p);
-       /* FIXME: if this is working we might have a string leak below */
-       g_object_unref (child_store);
+        /* recurse - with own store */
+        GtkTreeStore *child_store;
+        GtkTreeIter child_iter;
+
+        gtk_tree_model_get (model, iter, i, &child_store, -1);
+        if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (child_store), &child_iter)) {
+          _read_store (child_store, &child_iter, (ArrayProperty *) p);
+        }
+        /* FIXME: if this is working we might have a string leak below */
+        g_clear_object (&child_store);
       } else if (p->type_quark == g_quark_from_static_string (PROP_TYPE_BOOL))
        gtk_tree_model_get (model, iter, i, &((BoolProperty *)p)->bool_data, -1);
       else if (p->type_quark == g_quark_from_static_string (PROP_TYPE_INT))
@@ -740,7 +741,7 @@ _read_store (GtkTreeStore *store, GtkTreeIter *iter, ArrayProperty *prop)
        StringProperty *pst = (StringProperty *)p;
        gchar *value;
        gtk_tree_model_get (model, iter, i, &value, -1);
-       g_free (pst->string_data);
+       g_clear_pointer (&pst->string_data, g_free);
        pst->string_data = g_strdup (value);
       } else {
        /* only complain if we have a visible widget */
diff --git a/lib/prop_text.c b/lib/prop_text.c
index 358db12e..72b72aa8 100644
--- a/lib/prop_text.c
+++ b/lib/prop_text.c
@@ -78,8 +78,8 @@ stringprop_copy(StringProperty *src)
 static void
 stringprop_free(StringProperty *prop)
 {
-  g_free(prop->string_data);
-  g_free(prop);
+  g_clear_pointer (&prop->string_data, g_free);
+  g_clear_pointer (&prop, g_free);
 }
 
 static GtkWidget *
@@ -101,7 +101,7 @@ stringprop_reset_widget(StringProperty *prop, GtkWidget *widget)
 static void
 stringprop_set_from_widget(StringProperty *prop, GtkWidget *widget)
 {
-  g_free(prop->string_data);
+  g_clear_pointer (&prop->string_data, g_free);
   prop->string_data =
     g_strdup (gtk_entry_get_text (GTK_ENTRY(widget)));
 }
@@ -149,7 +149,7 @@ multistringprop_set_from_widget(StringProperty *prop, GtkWidget *widget) {
   GtkTextIter start, end;
   gtk_text_buffer_get_start_iter(buffer, &start);
   gtk_text_buffer_get_end_iter(buffer, &end);
-  g_free(prop->string_data);
+  g_clear_pointer (&prop->string_data, g_free);
   prop->string_data =
     g_strdup (gtk_text_buffer_get_text (buffer, &start, &end, TRUE));
 }
@@ -174,7 +174,7 @@ fileprop_reset_widget(StringProperty *prop, GtkWidget *widget)
 static void
 fileprop_set_from_widget(StringProperty *prop, GtkWidget *widget)
 {
-  g_free(prop->string_data);
+  g_clear_pointer (&prop->string_data, g_free);
   prop->string_data =
     g_strdup(dia_file_selector_get_file(DIAFILESELECTOR(widget)));
 }
@@ -182,7 +182,7 @@ fileprop_set_from_widget(StringProperty *prop, GtkWidget *widget)
 static void
 stringprop_load(StringProperty *prop, AttributeNode attr, DataNode data, DiaContext *ctx)
 {
-  g_free(prop->string_data);
+  g_clear_pointer (&prop->string_data, g_free);
   prop->string_data = data_string(data, ctx);
   if (prop->string_data == NULL) {
     prop->string_data = g_strdup("");
@@ -196,21 +196,27 @@ stringprop_save(StringProperty *prop, AttributeNode attr, DiaContext *ctx)
 }
 
 static void
-stringprop_get_from_offset(StringProperty *prop,
-                           void *base, guint offset, guint offset2)
+stringprop_get_from_offset (StringProperty *prop,
+                            void           *base,
+                            guint           offset,
+                            guint           offset2)
 {
-  g_free(prop->string_data);
-  prop->string_data = g_strdup(struct_member(base,offset,gchar *));
+  g_clear_pointer (&prop->string_data, g_free);
+  prop->string_data = g_strdup (struct_member (base, offset, char *));
 }
 
+
 static void
-stringprop_set_from_offset(StringProperty *prop,
-                           void *base, guint offset, guint offset2)
+stringprop_set_from_offset (StringProperty *prop,
+                            void           *base,
+                            guint           offset,
+                            guint           offset2)
 {
-  g_free(struct_member(base,offset,gchar *));
-  struct_member(base,offset,gchar *) = g_strdup(prop->string_data);
+  g_clear_pointer (&struct_member(base, offset, char *), g_free);
+  struct_member (base, offset, char *) = g_strdup (prop->string_data);
 }
 
+
 static int
 stringprop_get_data_size(StringProperty *prop)
 {
@@ -231,7 +237,7 @@ stringlistprop_free(StringListProperty *prop)
 {
   g_list_foreach(prop->string_list, (GFunc)g_free, NULL);
   g_list_free(prop->string_list);
-  g_free(prop);
+  g_clear_pointer (&prop, g_free);
 }
 
 static StringListProperty *
@@ -388,15 +394,15 @@ static void
 textprop_free (TextProperty *prop)
 {
   g_clear_object (&prop->attr.font);
-  g_free (prop->text_data);
-  g_free (prop);
+  g_clear_pointer (&prop->text_data, g_free);
+  g_clear_pointer (&prop, g_free);
 }
 
 static void
 textprop_load(TextProperty *prop, AttributeNode attr, DataNode data, DiaContext *ctx)
 {
   Text *text;
-  g_free(prop->text_data);
+  g_clear_pointer (&prop->text_data, g_free);
   text = data_text(data, ctx);
   text_get_attributes(text,&prop->attr);
   prop->text_data = text_get_string_copy(text);
@@ -421,7 +427,7 @@ textprop_get_from_offset(TextProperty *prop,
                          void *base, guint offset, guint offset2)
 {
   Text *text = struct_member(base,offset,Text *);
-  g_free(prop->text_data);
+  g_clear_pointer (&prop->text_data, g_free);
   prop->text_data = text_get_string_copy(text);
   text_get_attributes(text,&prop->attr);
 }
diff --git a/lib/prop_widgets.c b/lib/prop_widgets.c
index 906e977a..84562d99 100644
--- a/lib/prop_widgets.c
+++ b/lib/prop_widgets.c
@@ -131,8 +131,8 @@ frame_beginprop_get_widget(FrameProperty *prop, PropDialog *dialog)
 
   struct FoldButtonInfo *info = g_new(struct FoldButtonInfo, 1);
 
-  g_free(foldstring);
-  g_free(unfoldstring);
+  g_clear_pointer (&foldstring, g_free);
+  g_clear_pointer (&unfoldstring, g_free);
 
   info->frame = frame;
   info->unfoldbutton = unfoldbutton;
@@ -391,7 +391,7 @@ listprop_emptylines_realloc (ListProperty *prop, guint new_size) {
   guint i;
 
   for (i = 0; i < prop->lines->len; i++) {
-    g_free (g_ptr_array_index (prop->lines, i));
+    g_clear_pointer (&g_ptr_array_index (prop->lines, i), g_free);
   }
   g_ptr_array_set_size (prop->lines,new_size);
 }
diff --git a/lib/propdesc.c b/lib/propdesc.c
index dcb7cfdf..c8e1b6d3 100644
--- a/lib/propdesc.c
+++ b/lib/propdesc.c
@@ -74,15 +74,16 @@ prop_desc_find_real_handler(const PropDescription *pdesc)
   return ret;
 }
 
+
 /* free a handler indirection list */
 void
-prop_desc_free_handler_chain(PropDescription *pdesc)
+prop_desc_free_handler_chain (PropDescription *pdesc)
 {
   if (pdesc) {
     PropEventHandlerChain *chain = pdesc->chain_handler.chain;
     while (chain) {
       PropEventHandlerChain *next = chain->chain;
-      g_free(chain);
+      g_clear_pointer (&chain, g_free);
       chain = next;
     }
     pdesc->chain_handler.chain = NULL;
@@ -90,6 +91,7 @@ prop_desc_free_handler_chain(PropDescription *pdesc)
   }
 }
 
+
 /* free a handler indirection list in a list of descriptors */
 void
 prop_desc_list_free_handler_chain(PropDescription *pdesc)
diff --git a/lib/properties.h b/lib/properties.h
index dd712719..d311bfc3 100644
--- a/lib/properties.h
+++ b/lib/properties.h
@@ -458,7 +458,7 @@ void prop_list_add_filename (GPtrArray *plist, const char *name, const char *val
 /* adding an enum given an int */
 void prop_list_add_enum (GPtrArray *plist, const char *name, int val);
 /* adding a font */
-void prop_list_add_font (GPtrArray *plist, const char *name, const DiaFont *font);
+void prop_list_add_font (GPtrArray *plist, const char *name, DiaFont *font);
 /* add transformation matrix */
 void prop_list_add_matrix (GPtrArray *plist, const DiaMatrix *m);
 
diff --git a/lib/proplist.c b/lib/proplist.c
index 099076f1..34bdd6cf 100644
--- a/lib/proplist.c
+++ b/lib/proplist.c
@@ -186,7 +186,7 @@ prop_list_save(GPtrArray *props, DataNode data, DiaContext *ctx)
  * called prop_list_find_prop_by_name()
  */
 Property *
-find_prop_by_name(const GPtrArray *props, const gchar *name)
+find_prop_by_name (const GPtrArray *props, const char *name)
 {
   guint i;
   GQuark prop_quark = g_quark_from_string(name);
@@ -198,9 +198,11 @@ find_prop_by_name(const GPtrArray *props, const gchar *name)
   return NULL;
 }
 
+
 Property *
-find_prop_by_name_and_type(const GPtrArray *props, const gchar *name,
-                           PropertyType type)
+find_prop_by_name_and_type (const GPtrArray *props,
+                            const char      *name,
+                            PropertyType     type)
 {
   Property *ret = find_prop_by_name(props,name);
   GQuark type_quark = g_quark_from_string(type);
@@ -209,6 +211,7 @@ find_prop_by_name_and_type(const GPtrArray *props, const gchar *name,
   return ret;
 }
 
+
 void
 prop_list_add_list (GPtrArray *props, const GPtrArray *ptoadd)
 {
@@ -295,47 +298,53 @@ prop_list_add_fontsize (GPtrArray *plist, const char *name, real value)
   ((RealProperty *)prop)->real_data = value;
   g_ptr_array_add (plist, prop);
 }
+
+
 void
 prop_list_add_string (GPtrArray *plist, const char *name, const char *value)
 {
   Property *prop = make_new_prop (name, PROP_TYPE_STRING, 0);
 
-  g_free (((StringProperty *)prop)->string_data);
+  g_clear_pointer (&((StringProperty *) prop)->string_data, g_free);
   ((StringProperty *)prop)->string_data = g_strdup (value);
   g_ptr_array_add (plist, prop);
 }
+
+
 void
 prop_list_add_text (GPtrArray *plist, const char *name, const char *value)
 {
   Property *prop = make_new_prop (name, PROP_TYPE_TEXT, 0);
 
-  g_free (((TextProperty *)prop)->text_data);
+  g_clear_pointer (&((TextProperty *) prop)->text_data, g_free);
   ((TextProperty *)prop)->text_data = g_strdup (value);
   g_ptr_array_add (plist, prop);
 }
+
+
 void
 prop_list_add_filename (GPtrArray *plist, const char *name, const char *value)
 {
   Property *prop = make_new_prop (name, PROP_TYPE_FILE, 0);
 
-  g_free (((StringProperty *)prop)->string_data);
+  g_clear_pointer (&((StringProperty *) prop)->string_data, g_free);
   ((StringProperty *)prop)->string_data = g_strdup (value);
   g_ptr_array_add (plist, prop);
 }
 
+
 void
-prop_list_add_font (GPtrArray *plist, const char *name, const DiaFont *font)
+prop_list_add_font (GPtrArray *plist, const char *name, DiaFont *font)
 {
   Property *prop = make_new_prop (name, PROP_TYPE_FONT, 0);
   FontProperty *fp = (FontProperty *)prop;
 
-  if (fp->font_data == font)
-    return;
-  if (fp->font_data)
-    g_object_unref (fp->font_data);
-  fp->font_data = g_object_ref ((gpointer)font);
-  g_ptr_array_add (plist, prop);
+  if (g_set_object (&fp->font_data, font)) {
+    g_ptr_array_add (plist, prop);
+  }
 }
+
+
 void
 prop_list_add_enum (GPtrArray *plist, const char *name, int value)
 {
@@ -344,17 +353,21 @@ prop_list_add_enum (GPtrArray *plist, const char *name, int value)
   ((EnumProperty *)prop)->enum_data = value;
   g_ptr_array_add (plist, prop);
 }
+
+
 void
 prop_list_add_text_colour (GPtrArray *plist, const Color *color)
 {
   _prop_list_add_colour (plist, "text_colour", color);
 }
+
+
 void
 prop_list_add_matrix (GPtrArray *plist, const DiaMatrix *m)
 {
   Property *prop = make_new_prop ("matrix", PROP_TYPE_MATRIX, 0);
 
-  g_free (((MatrixProperty *)prop)->matrix);
+  g_clear_pointer (&((MatrixProperty *) prop)->matrix, g_free);
   (( MatrixProperty *)prop)->matrix = g_memdup (m, sizeof(DiaMatrix));
   g_ptr_array_add (plist, prop);
 }
diff --git a/lib/propobject.c b/lib/propobject.c
index a869414d..a38f1073 100644
--- a/lib/propobject.c
+++ b/lib/propobject.c
@@ -399,9 +399,7 @@ dia_object_set_pixbuf (DiaObject *object,
   pp = (PixbufProperty *)prop;
   if (pp->pixbuf == pixbuf)
     return change_list_create ();
-  if (pp->pixbuf)
-    g_object_unref (pp->pixbuf);
-  pp->pixbuf = g_object_ref (pixbuf);
+  g_set_object (&pp->pixbuf, pixbuf);
   props = prop_list_from_single (prop);
   change = object_apply_props (object, props);
   prop_list_free (props);
@@ -436,9 +434,7 @@ dia_object_set_pattern (DiaObject  *object,
   pp = (PatternProperty *)prop;
   if (pp->pattern == pattern)
     return change_list_create ();
-  if (pp->pattern)
-    g_object_unref (pp->pattern);
-  pp->pattern = g_object_ref (pattern);
+  g_set_object (&pp->pattern, pattern);
   props = prop_list_from_single (prop);
   change = object_apply_props (object, props);
   prop_list_free (props);
@@ -471,12 +467,12 @@ dia_object_set_string (DiaObject *object,
     prop = object_prop_by_name_type (object, name, PROP_TYPE_FILE);
   if (prop) {
     StringProperty *pp = (StringProperty *)prop;
-    g_free (pp->string_data);
+    g_clear_pointer (&pp->string_data, g_free);
     pp->string_data = g_strdup (value);
     props = prop_list_from_single (prop);
   } else if ((prop = object_prop_by_name_type (object, name, PROP_TYPE_TEXT)) != NULL) {
     TextProperty *pp = (TextProperty *)prop;
-    g_free (pp->text_data);
+    g_clear_pointer (&pp->text_data, g_free);
     pp->text_data = g_strdup (value);
     props = prop_list_from_single (prop);
   }
diff --git a/lib/renderer/diacairo-interactive.c b/lib/renderer/diacairo-interactive.c
index 22726432..a1fcc19c 100644
--- a/lib/renderer/diacairo-interactive.c
+++ b/lib/renderer/diacairo-interactive.c
@@ -249,7 +249,7 @@ dia_cairo_interactive_renderer_get_text_width (DiaRenderer *object,
     }
     shorter = g_strndup (text, ulen);
     text_line = text_line_new (shorter, font, font_height);
-    g_free (shorter);
+    g_clear_pointer (&shorter, g_free);
   } else {
     text_line = text_line_new (text, font, font_height);
   }
@@ -388,7 +388,7 @@ dia_cairo_interactive_renderer_clip_region_add_rect (DiaInteractiveRenderer *obj
   transform = dia_transform_new (renderer->visible,renderer->zoom_factor);
   dia_transform_coords (transform, rect->left, rect->top, &x1, &y1);
   dia_transform_coords (transform, rect->right, rect->bottom, &x2, &y2);
-  g_object_unref (transform);
+  g_clear_object (&transform);
 
   clip_rect.x = x1;
   clip_rect.y = y1;
diff --git a/lib/renderer/diacairo-print.c b/lib/renderer/diacairo-print.c
index 73402797..dbcccc51 100644
--- a/lib/renderer/diacairo-print.c
+++ b/lib/renderer/diacairo-print.c
@@ -179,17 +179,19 @@ draw_page (GtkPrintOperation *operation,
   cairo_restore (cairo_renderer->cr);
 }
 
+
 static void
 end_print (GtkPrintOperation *operation,
            GtkPrintContext   *context,
            PrintData         *print_data)
 {
-  g_object_unref (print_data->data);
-  g_object_unref (print_data->renderer);
+  g_clear_object (&print_data->data);
+  g_clear_object (&print_data->renderer);
 
-  g_free (print_data);
+  g_clear_pointer (&print_data, g_free);
 }
 
+
 GtkPrintOperation *
 create_print_operation (DiagramData *data, const char *name)
 {
@@ -212,7 +214,7 @@ create_print_operation (DiagramData *data, const char *name)
     setup = gtk_page_setup_new ();
   _dia_to_gtk_page_setup (print_data->data, setup);
   gtk_print_operation_set_default_page_setup (operation, setup);
-  g_object_unref (setup);
+  g_clear_object (&setup);
 
   /* similar logic draw_page() but we need to set the total pages in advance */
   if (data->paper.fitto) {
@@ -233,20 +235,26 @@ create_print_operation (DiagramData *data, const char *name)
   return operation;
 }
 
+
 ObjectChange *
 cairo_print_callback (DiagramData *data,
-                      const gchar *filename,
-                      guint flags, /* further additions */
-                      void *user_data)
+                      const char  *filename,
+                      guint        flags, /* further additions */
+                      void        *user_data)
 {
   GtkPrintOperation *op = create_print_operation (data, filename ? filename : "diagram");
   GtkPrintOperationResult res;
   GError *error = NULL;
 
-  res = gtk_print_operation_run (op, GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG, NULL, &error);
+  res = gtk_print_operation_run (op,
+                                 GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
+                                 NULL,
+                                 &error);
+
   if (GTK_PRINT_OPERATION_RESULT_ERROR == res) {
     message_error ("%s", error->message);
-    g_error_free (error);
+    g_clear_error (&error);
   }
+
   return NULL;
 }
diff --git a/lib/renderer/diacairo-renderer.c b/lib/renderer/diacairo-renderer.c
index edefdf31..db852a59 100644
--- a/lib/renderer/diacairo-renderer.c
+++ b/lib/renderer/diacairo-renderer.c
@@ -227,6 +227,7 @@ dia_cairo_renderer_is_capable_to (DiaRenderer      *renderer,
   return FALSE;
 }
 
+
 /*!
  * \brief Remember the given pattern to use for consecutive fill
  * @param self explicit this pointer
@@ -237,19 +238,11 @@ dia_cairo_renderer_set_pattern (DiaRenderer *self,
                                 DiaPattern  *pattern)
 {
   DiaCairoRenderer *renderer = DIA_CAIRO_RENDERER (self);
-  DiaPattern *prev = renderer->pattern;
-
-  if (pattern) {
-    renderer->pattern = g_object_ref (pattern);
-  } else {
-    renderer->pattern = pattern;
-  }
 
-  if (prev) {
-    g_object_unref (prev);
-  }
+  g_set_object (&renderer->pattern, pattern);
 }
 
+
 static gboolean
 _add_color_stop (real ofs, const Color *col, gpointer user_data)
 {
@@ -1259,10 +1252,8 @@ cairo_renderer_finalize (GObject *object)
   if (renderer->surface) {
     cairo_surface_destroy (renderer->surface);
   }
-  if (renderer->layout) {
-    g_object_unref (renderer->layout);
-  }
 
+  g_clear_object (&renderer->layout);
   g_clear_object (&renderer->font);
 
   G_OBJECT_CLASS (dia_cairo_renderer_parent_class)->finalize (object);
diff --git a/lib/renderer/diacairo.c b/lib/renderer/diacairo.c
index 25a4c531..bda0febb 100644
--- a/lib/renderer/diacairo.c
+++ b/lib/renderer/diacairo.c
@@ -276,7 +276,7 @@ cairo_export_data (DiagramData *data,
       dia_context_add_message(ctx, _("Can't write %d bytes to %s"), nSize, filename);
     }
     DeleteEnhMetaFile (hEmf);
-    g_free (pData);
+    g_clear_pointer (&pData, g_free);
   } else if (OUTPUT_WMF == kind) {
     FILE* f = g_fopen(filename, "wb");
     HENHMETAFILE hEmf = CloseEnhMetaFile(hFileDC);
@@ -293,7 +293,7 @@ cairo_export_data (DiagramData *data,
     }
     ReleaseDC(NULL, hdc);
     DeleteEnhMetaFile (hEmf);
-    g_free (pData);
+    g_clear_pointer (&pData, g_free);
   } else if (OUTPUT_CLIPBOARD == kind) {
     HENHMETAFILE hEmf = CloseEnhMetaFile(hFileDC);
     if (   OpenClipboard(NULL)
@@ -307,9 +307,9 @@ cairo_export_data (DiagramData *data,
     }
   }
 #endif
-  g_object_unref(renderer);
+  g_clear_object (&renderer);
   if (filename != filename_crt)
-    g_free (filename_crt);
+    g_clear_pointer (&filename_crt, g_free);
   return TRUE;
 }
 
@@ -336,10 +336,12 @@ export_print_data (DiagramData *data, DiaContext *ctx,
 
   gtk_print_operation_set_export_filename (op, filename_utf8 ? filename_utf8 : "output.pdf");
   res = gtk_print_operation_run (op, GTK_PRINT_OPERATION_ACTION_EXPORT, NULL, &error);
+
   if (GTK_PRINT_OPERATION_RESULT_ERROR == res) {
-    dia_context_add_message(ctx, "%s", error->message);
-    g_error_free (error);
+    dia_context_add_message (ctx, "%s", error->message);
+    g_clear_error (&error);
     return FALSE;
   }
+
   return TRUE;
 }
diff --git a/lib/sheet.c b/lib/sheet.c
index 494a91b4..2c54883b 100644
--- a/lib/sheet.c
+++ b/lib/sheet.c
@@ -45,7 +45,7 @@ static GSList *sheets = NULL;
 
 Sheet *
 new_sheet (char       *name,
-           gchar      *description,
+           char       *description,
            char       *filename,
            SheetScope  scope,
            Sheet      *shadowing)
@@ -110,15 +110,16 @@ get_sheets_list (void)
 
 /* Sheet file management */
 
-static void load_sheets_from_dir (const gchar *directory,
-                                  SheetScope   scope);
-static void load_register_sheet  (const gchar *directory,
-                                  const gchar *filename,
-                                  SheetScope   scope);
+static void load_sheets_from_dir (const char *directory,
+                                  SheetScope  scope);
+static void load_register_sheet  (const char *directory,
+                                  const char *filename,
+                                  SheetScope  scope);
+
 
 /** Sort the list of sheets by *locale*.
  */
-static gint
+static int
 dia_sheet_sort_callback (gconstpointer a, gconstpointer b)
 {
   // TODO: Don't gettext random strings
@@ -142,7 +143,7 @@ load_all_sheets (void)
   if (home_dir) {
     dia_log_message ("sheets from '%s'", home_dir);
     load_sheets_from_dir (home_dir, SHEET_SCOPE_USER);
-    g_free (home_dir);
+    g_clear_pointer (&home_dir, g_free);
   }
 
   sheet_path = getenv ("DIA_SHEET_PATH");
@@ -159,7 +160,7 @@ load_all_sheets (void)
     char *thedir = dia_get_data_directory ("sheets");
     dia_log_message ("sheets from '%s'", thedir);
     load_sheets_from_dir (thedir, SHEET_SCOPE_SYSTEM);
-    g_free (thedir);
+    g_clear_pointer (&thedir, g_free);
   }
 
   /* Sorting their sheets alphabetically makes user merging easier */
@@ -167,13 +168,14 @@ load_all_sheets (void)
   dia_sort_sheets ();
 }
 
+
 static void
-load_sheets_from_dir (const gchar *directory,
-                      SheetScope   scope)
+load_sheets_from_dir (const char *directory,
+                      SheetScope  scope)
 {
   GDir *dp;
   const char *dentry;
-  gchar *p;
+  char *p;
 
   dp = g_dir_open (directory, 0, NULL);
   if (!dp) {
@@ -181,38 +183,39 @@ load_sheets_from_dir (const gchar *directory,
   }
 
   while ((dentry = g_dir_read_name (dp))) {
-    gchar *filename = g_strconcat (directory, G_DIR_SEPARATOR_S, dentry, NULL);
+    char *filename = g_strconcat (directory, G_DIR_SEPARATOR_S, dentry, NULL);
 
     if (!g_file_test (filename, G_FILE_TEST_IS_REGULAR)) {
-      g_free (filename);
+      g_clear_pointer (&filename, g_free);
       continue;
     }
 
     /* take only .sheet files */
     p = filename + strlen (filename) - 6 /* strlen(".sheet") */;
     if (0 != strncmp (p, ".sheet", 6)) {
-      g_free (filename);
+      g_clear_pointer (&filename, g_free);
       continue;
     }
 
     load_register_sheet (directory, filename, scope);
-    g_free (filename);
+    g_clear_pointer (&filename, g_free);
   }
 
   g_dir_close (dp);
 }
 
+
 static void
-load_register_sheet (const gchar *dirname,
-                     const gchar *filename,
-                     SheetScope   scope)
+load_register_sheet (const char *dirname,
+                     const char *filename,
+                     SheetScope  scope)
 {
   xmlErrorPtr error_xml = NULL;
   xmlDocPtr doc;
   xmlNsPtr ns;
   xmlNodePtr node, contents,subnode,root;
   xmlChar *tmp;
-  gchar *name = NULL, *description = NULL;
+  char *name = NULL, *description = NULL;
   int name_score = -1;
   int descr_score = -1;
   Sheet *sheet = NULL;
@@ -270,7 +273,7 @@ load_register_sheet (const gchar *dirname,
     }
 
     if (node->ns == ns && !xmlStrcmp (node->name, (const xmlChar *) "name")) {
-      gint score;
+      int score;
 
       /* compare the xml:lang property on this element to see if we get a
        * better language match.  LibXML seems to throw away attribute
@@ -296,7 +299,7 @@ load_register_sheet (const gchar *dirname,
         name = (char *) xmlNodeGetContent (node);
       }
     } else if (node->ns == ns && !xmlStrcmp (node->name, (const xmlChar *) "description")) {
-      gint score;
+      int score;
 
       /* compare the xml:lang property on this element to see if we get a
        * better language match.  LibXML seems to throw away attribute
@@ -350,7 +353,7 @@ load_register_sheet (const gchar *dirname,
       g_assert (!stat_ret);
 
       if (this_file.st_mtime > first_file.st_mtime) {
-        gchar *tmp2 = g_strdup_printf ("%s [Copy of system]", name);
+        char *tmp2 = g_strdup_printf ("%s [Copy of system]", name);
         message_notice (_("The system sheet '%s' appears to be more recent"
                           " than your custom\n"
                           "version and has been loaded as '%s' for this session."
@@ -380,7 +383,7 @@ load_register_sheet (const gchar *dirname,
   }
 
   if (name_is_gmalloced == TRUE) {
-    g_free (name);
+    g_clear_pointer (&name, g_free);
   } else {
     xmlFree (name);
   }
@@ -389,20 +392,20 @@ load_register_sheet (const gchar *dirname,
   for (node = contents->xmlChildrenNode; node != NULL; node = node->next) {
     SheetObject *sheet_obj;
     DiaObjectType *otype;
-    gchar *iconname = NULL;
+  char *iconname = NULL;
 
     int subdesc_score = -1;
     xmlChar *objdesc = NULL;
 
-    gint intdata = 0;
-    gchar *chardata = NULL;
+    int intdata = 0;
+    char *chardata = NULL;
 
     gboolean has_intdata = FALSE;
     gboolean has_icon_on_sheet = FALSE;
 
     xmlChar *ot_name = NULL;
 
-    gchar *sheetdir = dia_get_data_directory ("sheets");
+    char *sheetdir = dia_get_data_directory ("sheets");
 
     if (xmlIsBlankNode (node)) {
       continue;
@@ -432,12 +435,12 @@ load_register_sheet (const gchar *dirname,
     tmp = xmlGetProp (node, (const xmlChar *) "intdata");
     if (tmp) {
       char *p;
-      intdata = (gint) strtol ((char *) tmp, &p, 0);
+      intdata = (int) strtol ((char *) tmp, &p, 0);
       if (*p != 0) intdata = 0;
       xmlFree (tmp);
       has_intdata = TRUE;
     }
-    chardata = (gchar *) xmlGetProp (node, (const xmlChar *) "chardata");
+    chardata = (char *) xmlGetProp (node, (const xmlChar *) "chardata");
     /* TODO.... */
     if (chardata) {
       xmlFree (chardata);
@@ -453,7 +456,7 @@ load_register_sheet (const gchar *dirname,
       }
 
       if (subnode->ns == ns && !xmlStrcmp (subnode->name, (const xmlChar *) "description")) {
-        gint score;
+        int score;
 
         /* compare the xml:lang property on this element to see if we get a
         * better language match.  LibXML seems to throw away attribute
@@ -497,7 +500,7 @@ load_register_sheet (const gchar *dirname,
       }
     }
 
-    g_free (sheetdir);
+    g_clear_pointer (&sheetdir, g_free);
 
     sheet_obj = g_new (SheetObject, 1);
     sheet_obj->object_type = g_strdup ((char *) ot_name);
@@ -523,12 +526,10 @@ load_register_sheet (const gchar *dirname,
     if ((otype = object_get_type ((char *) ot_name)) == NULL) {
       /* Don't complain. This does happen when disabling plug-ins too.
       g_warning("object_get_type(%s) returned NULL", tmp); */
-      if (sheet_obj->description) {
-        g_free (sheet_obj->description);
-      }
-      g_free (sheet_obj->pixmap_file);
-      g_free (sheet_obj->object_type);
-      g_free (sheet_obj);
+      g_clear_pointer (&sheet_obj->description, g_free);
+      g_clear_pointer (&sheet_obj->pixmap_file, g_free);
+      g_clear_pointer (&sheet_obj->object_type, g_free);
+      g_clear_pointer (&sheet_obj, g_free);
       if (tmp) {
         xmlFree (ot_name);
       }
diff --git a/lib/standard-path.c b/lib/standard-path.c
index ac35a186..61679d24 100644
--- a/lib/standard-path.c
+++ b/lib/standard-path.c
@@ -285,7 +285,7 @@ stdpath_create (Point *startpoint,
       g_warning ("'Standard - Path' needs at least two points");
       /* this is a stress test - object might not be setup completely */
       object_destroy (obj);
-      g_free (stdpath);
+      g_clear_pointer (&stdpath, g_free);
       return NULL;
     }
     stdpath->num_points = bcd->num_points;
@@ -1022,6 +1022,8 @@ stdpath_copy (StdPath *from)
   to = object_copy_using_properties (&from->object);
   return to;
 }
+
+
 /*!
  * \brief Destruction of the object
  * \memberof _StdPath
@@ -1029,12 +1031,13 @@ stdpath_copy (StdPath *from)
 static void
 stdpath_destroy (StdPath *stdpath)
 {
-  object_destroy(&stdpath->object);
-  if (stdpath->pattern)
-    g_object_unref (stdpath->pattern);
-  g_free (stdpath->points);
+  object_destroy (&stdpath->object);
+  g_clear_object (&stdpath->pattern);
+  g_clear_pointer (&stdpath->points, g_free);
   /* but not the object itself */
 }
+
+
 /*!
  * \brief Change the object state regarding selection
  * \memberof _StdPath
@@ -1086,7 +1089,7 @@ text_to_path (const Text *text, GArray *points)
 
   str = text_get_string_copy (text);
   pango_layout_set_text (layout, str, -1);
-  g_free (str);
+  g_clear_pointer (&str, g_free);
 
   pango_layout_get_extents (layout, &ink_rect, NULL);
   /* any surface should do - this one is always available */
@@ -1137,7 +1140,7 @@ text_to_path (const Text *text, GArray *points)
   /* finally scale it ? */
 
   /* clean up */
-  g_object_unref (layout);
+  g_clear_object (&layout);
   cairo_destroy (cr);
 
   return ret;
diff --git a/lib/text.c b/lib/text.c
index a60f74c7..fd744e1f 100644
--- a/lib/text.c
+++ b/lib/text.c
@@ -101,7 +101,7 @@ text_delete_line(Text *text, int line_no)
 {
   int i;
 
-  g_free(text->lines[line_no]);
+  g_clear_pointer (&text->lines[line_no], g_free);
   for (i = line_no; i < text->numlines - 1; i++) {
     text->lines[i] = text->lines[i+1];
   }
@@ -215,8 +215,7 @@ free_string(Text *text)
     text_line_destroy(text->lines[i]);
   }
 
-  g_free(text->lines);
-  text->lines = NULL;
+  g_clear_pointer (&text->lines, g_free);
 }
 
 static void
@@ -264,7 +263,7 @@ set_string(Text *text, const char *string)
     }
     string_line = g_strndup(s, s2 - s);
     text_set_line_text(text, i, string_line);
-    g_free(string_line);
+    g_clear_pointer (&string_line, g_free);
     s = s2;
     if (*s) {
       s = g_utf8_next_char(s);
@@ -278,7 +277,7 @@ set_string(Text *text, const char *string)
   if (text->cursor_pos > text_get_line_strlen(text, text->cursor_row)) {
     text->cursor_pos = text_get_line_strlen(text, text->cursor_row);
   }
-  g_free (fallback);
+  g_clear_pointer (&fallback, g_free);
 }
 
 void
@@ -383,7 +382,7 @@ text_destroy (Text *text)
 {
   free_string (text);
   g_clear_object (&text->font);
-  g_free (text);
+  g_clear_pointer (&text, g_free);
 }
 
 void
@@ -763,7 +762,7 @@ text_join_lines(Text *text, int first_line)
                              text_get_line(text, first_line + 1), NULL);
   text_delete_line(text, first_line);
   text_set_line_text(text, first_line, combined_line);
-  g_free(combined_line);
+  g_clear_pointer (&combined_line, g_free);
 
   text->max_width = MAX(text->max_width, text_get_line_width(text, first_line));
 
@@ -771,15 +770,16 @@ text_join_lines(Text *text, int first_line)
   text->cursor_pos = len1;
 }
 
+
 static void
-text_delete_forward(Text *text)
+text_delete_forward (Text *text)
 {
   int row;
   int i;
-  real width;
-  gchar *line;
-  gchar *utf8_before, *utf8_after;
-  gchar *str1, *str;
+  double width;
+  char *line;
+  char *utf8_before, *utf8_after;
+  char *str1, *str;
 
   row = text->cursor_row;
 
@@ -795,8 +795,8 @@ text_delete_forward(Text *text)
   str1 = g_strndup(line, utf8_before - line);
   str = g_strconcat(str1, utf8_after, NULL);
   text_set_line_text(text, row, str);
-  g_free(str1);
-  g_free(str);
+  g_clear_pointer (&str1, g_free);
+  g_clear_pointer (&str, g_free);
 
   if (text->cursor_pos > text_get_line_strlen(text, text->cursor_row))
     text->cursor_pos = text_get_line_strlen(text, text->cursor_row);
@@ -808,15 +808,16 @@ text_delete_forward(Text *text)
   text->max_width = width;
 }
 
+
 static void
-text_delete_backward(Text *text)
+text_delete_backward (Text *text)
 {
   int row;
   int i;
-  real width;
-  gchar *line;
-  gchar *utf8_before, *utf8_after;
-  gchar *str1, *str;
+  double width;
+  char *line;
+  char *utf8_before, *utf8_after;
+  char *str1, *str;
 
   row = text->cursor_row;
 
@@ -832,8 +833,8 @@ text_delete_backward(Text *text)
   str1 = g_strndup(line, utf8_before - line);
   str = g_strconcat(str1, utf8_after, NULL);
   text_set_line_text(text, row, str);
-  g_free(str);
-  g_free(str1);
+  g_clear_pointer (&str, g_free);
+  g_clear_pointer (&str1, g_free);
 
   text->cursor_pos --;
   if (text->cursor_pos > text_get_line_strlen(text, text->cursor_row))
@@ -847,13 +848,13 @@ text_delete_backward(Text *text)
 }
 
 static void
-text_split_line(Text *text)
+text_split_line (Text *text)
 {
   int i;
   char *line;
-  real width;
-  gchar *utf8_before;
-  gchar *str1, *str2;
+  double width;
+  char *utf8_before;
+  char *str1, *str2;
 
   /* Split the lines at cursor_pos */
   line = text_get_line(text, text->cursor_row);
@@ -863,8 +864,8 @@ text_split_line(Text *text)
   str2 = g_strdup(utf8_before); /* Must copy before dealloc */
   text_set_line_text(text, text->cursor_row, str1);
   text_set_line_text(text, text->cursor_row + 1, str2);
-  g_free(str2);
-  g_free(str1);
+  g_clear_pointer (&str2, g_free);
+  g_clear_pointer (&str1, g_free);
 
   text->cursor_row ++;
   text->cursor_pos = 0;
@@ -876,15 +877,16 @@ text_split_line(Text *text)
   text->max_width = width;
 }
 
+
 static void
-text_insert_char(Text *text, gunichar c)
+text_insert_char (Text *text, gunichar c)
 {
-  gchar ch[7];
+  char ch[7];
   int unilen;
   int row;
-  gchar *line, *str;
-  gchar *utf8_before;
-  gchar *str1;
+  char *line, *str;
+  char *utf8_before;
+  char *str1;
 
   /* Make a string of the the char */
   unilen = g_unichar_to_utf8 (c, ch);
@@ -898,8 +900,8 @@ text_insert_char(Text *text, gunichar c)
   str1 = g_strndup(line, utf8_before - line);
   str = g_strconcat(str1, ch, utf8_before, NULL);
   text_set_line_text(text, row, str);
-  g_free(str);
-  g_free(str1);
+  g_clear_pointer (&str, g_free);
+  g_clear_pointer (&str1, g_free);
 
   text->cursor_pos++;
   text->max_width = MAX(text->max_width, text_get_line_width(text, row));
@@ -1104,7 +1106,7 @@ data_add_text(AttributeNode attr, Text *text, DiaContext *ctx)
   str = text_get_string_copy(text);
   data_add_string(composite_add_attribute(composite, "string"),
                  str, ctx);
-  g_free(str);
+  g_clear_pointer (&str, g_free);
   data_add_font(composite_add_attribute(composite, "font"),
                text->font, ctx);
   data_add_real(composite_add_attribute(composite, "height"),
@@ -1162,7 +1164,7 @@ data_text(AttributeNode text_attr, DiaContext *ctx)
 
   text = new_text (string ? string : "", font, height, &pos, &col, align);
   g_clear_object (&font);
-  if (string) g_free(string);
+  g_clear_pointer (&string, g_free);
   return text;
 }
 
@@ -1280,7 +1282,7 @@ text_change_revert(struct TextObjectChange *change, DiaObject *obj)
 static void
 text_change_free (struct TextObjectChange *change)
 {
-  g_free (change->str);
+  g_clear_pointer (&change->str, g_free);
   prop_list_free (change->props);
 }
 
diff --git a/lib/textline.c b/lib/textline.c
index f94febdd..691a0442 100644
--- a/lib/textline.c
+++ b/lib/textline.c
@@ -39,13 +39,11 @@ static void clear_layout_offset (TextLine *text_line);
  * \memberof TextLine
  */
 void
-text_line_set_string(TextLine *text_line, const gchar *string)
+text_line_set_string (TextLine *text_line, const char *string)
 {
   if (text_line->chars == NULL ||
-      strcmp(text_line->chars, string)) {
-    if (text_line->chars != NULL) {
-      g_free(text_line->chars);
-    }
+      strcmp (text_line->chars, string)) {
+    g_clear_pointer (&text_line->chars, g_free);
 
     text_line->chars = g_strdup(string);
 
@@ -125,12 +123,10 @@ text_line_copy(const TextLine *text_line)
 void
 text_line_destroy (TextLine *text_line)
 {
-  if (text_line->chars != NULL) {
-    g_free (text_line->chars);
-  }
+  g_clear_pointer (&text_line->chars, g_free);
   g_clear_object (&text_line->font);
   clear_layout_offset (text_line);
-  g_free (text_line->offsets);
+  g_clear_pointer (&text_line->offsets, g_free);
   g_free (text_line);
 }
 
@@ -240,12 +236,11 @@ clear_layout_offset (TextLine *text_line)
     for (; runs != NULL; runs = g_slist_next(runs)) {
       PangoGlyphItem *run = (PangoGlyphItem *) runs->data;
 
-      g_free(run->glyphs->glyphs);
-      g_free(run->glyphs);
+      g_clear_pointer (&run->glyphs->glyphs, g_free);
+      g_clear_pointer (&run->glyphs, g_free);
     }
     g_slist_free(runs);
-    g_free(text_line->layout_offsets);
-    text_line->layout_offsets = NULL;
+    g_clear_pointer (&text_line->layout_offsets, g_free);
   }
 }
 
@@ -258,10 +253,7 @@ text_line_cache_values(TextLine *text_line)
       text_line->height != text_line->height_cache) {
     int n_offsets;
 
-    if (text_line->offsets != NULL) {
-      g_free(text_line->offsets);
-      text_line->offsets = NULL;
-    }
+    g_clear_pointer (&text_line->offsets, g_free);
     clear_layout_offset (text_line);
 
     if (text_line->chars == NULL ||
@@ -273,7 +265,7 @@ text_line_cache_values(TextLine *text_line)
                           &text_line->descent, &n_offsets,
                           &text_line->layout_offsets);
       clear_layout_offset (text_line);
-      g_free (text_line->offsets);
+      g_clear_pointer (&text_line->offsets, g_free);
       text_line->offsets = g_new (real,0); /* another way to assign NULL;) */
       text_line->width = 0;
     } else {
diff --git a/lib/widgets.c b/lib/widgets.c
index 5a5bfe05..fcf86eec 100644
--- a/lib/widgets.c
+++ b/lib/widgets.c
@@ -296,8 +296,8 @@ struct _DiaFileSelector
   GtkEntry *entry;
   GtkButton *browse;
   GtkWidget *dialog;
-  gchar *sys_filename;
-  gchar *pattern; /* for supported formats */
+  char *sys_filename;
+  char *pattern; /* for supported formats */
 };
 
 struct _DiaFileSelectorClass
@@ -321,14 +321,8 @@ dia_file_selector_unrealize(GtkWidget *widget)
     gtk_widget_destroy(GTK_WIDGET(fs->dialog));
     fs->dialog = NULL;
   }
-  if (fs->sys_filename) {
-    g_free(fs->sys_filename);
-    fs->sys_filename = NULL;
-  }
-  if (fs->pattern) {
-    g_free (fs->pattern);
-    fs->pattern = NULL;
-  }
+  g_clear_pointer (&fs->sys_filename, g_free);
+  g_clear_pointer (&fs->pattern, g_free);
 
   (* GTK_WIDGET_CLASS (g_type_class_peek_parent (G_OBJECT_GET_CLASS (fs)))->unrealize) (widget);
 }
@@ -358,6 +352,7 @@ dia_file_selector_entry_changed(GtkEditable *editable
   g_signal_emit(fs, dfile_signals[DFILE_VALUE_CHANGED], 0);
 }
 
+
 static void
 file_open_response_callback(GtkWidget *dialog,
                             gint       response,
@@ -367,20 +362,22 @@ file_open_response_callback(GtkWidget *dialog,
     DIAFILESELECTOR(g_object_get_data(G_OBJECT(dialog), "user_data"));
 
   if (response == GTK_RESPONSE_ACCEPT || response == GTK_RESPONSE_OK) {
-    gchar *utf8 = g_filename_to_utf8(gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)),
+    char *utf8 = g_filename_to_utf8 (gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog)),
                             -1, NULL, NULL, NULL);
-    gtk_entry_set_text(GTK_ENTRY(fs->entry), utf8);
-    g_free(utf8);
+    gtk_entry_set_text (GTK_ENTRY (fs->entry), utf8);
+    g_clear_pointer (&utf8, g_free);
   }
-  gtk_widget_destroy(GTK_WIDGET(dialog));
+
+  gtk_widget_destroy (GTK_WIDGET (dialog));
 }
 
+
 static void
-dia_file_selector_browse_pressed(GtkWidget *widget, gpointer data)
+dia_file_selector_browse_pressed (GtkWidget *widget, gpointer data)
 {
   GtkWidget *dialog;
   DiaFileSelector *fs = DIAFILESELECTOR(data);
-  gchar *filename;
+  char *filename;
   GtkWidget *toplevel = gtk_widget_get_toplevel (widget);
 
   if (toplevel && !GTK_WINDOW(toplevel))
@@ -423,7 +420,7 @@ dia_file_selector_browse_pressed(GtkWidget *widget, gpointer data)
   if (g_path_is_absolute(filename))
     gtk_file_chooser_set_filename(GTK_FILE_CHOOSER(fs->dialog), filename);
 
-  g_free(filename);
+  g_clear_pointer (&filename, g_free);
 
   gtk_widget_show(GTK_WIDGET(fs->dialog));
 }
@@ -482,12 +479,12 @@ dia_file_selector_new (void)
 }
 
 void
-dia_file_selector_set_extensions  (DiaFileSelector *fs, const gchar **exts)
+dia_file_selector_set_extensions  (DiaFileSelector *fs, const char **exts)
 {
   GString *pattern = g_string_new ("*.");
   int i = 0;
 
-  g_free (fs->pattern);
+  g_clear_pointer (&fs->pattern, g_free);
 
   while (exts[i] != NULL) {
     if (i != 0)
@@ -499,20 +496,22 @@ dia_file_selector_set_extensions  (DiaFileSelector *fs, const gchar **exts)
   g_string_free (pattern, FALSE);
 }
 
+
 void
-dia_file_selector_set_file(DiaFileSelector *fs, gchar *file)
+dia_file_selector_set_file (DiaFileSelector *fs, char *file)
 {
   /* filename is in system encoding */
-  gchar *utf8 = g_filename_to_utf8(file, -1, NULL, NULL, NULL);
-  gtk_entry_set_text(GTK_ENTRY(fs->entry), utf8);
-  g_free(utf8);
+  char *utf8 = g_filename_to_utf8 (file, -1, NULL, NULL, NULL);
+  gtk_entry_set_text (GTK_ENTRY (fs->entry), utf8);
+  g_clear_pointer (&utf8, g_free);
 }
 
-const gchar *
+
+const char *
 dia_file_selector_get_file(DiaFileSelector *fs)
 {
   /* let it behave like gtk_file_selector_get_file */
-  g_free(fs->sys_filename);
+  g_clear_pointer (&fs->sys_filename, g_free);
   fs->sys_filename = g_filename_from_utf8(gtk_entry_get_text(GTK_ENTRY(fs->entry)),
                                           -1, NULL, NULL, NULL);
   return fs->sys_filename;
@@ -593,11 +592,12 @@ dia_unit_spinner_new(GtkAdjustment *adjustment, DiaUnit adj_unit)
   return GTK_WIDGET(self);
 }
 
+
 static gboolean
-dia_unit_spinner_input(DiaUnitSpinner *self, gdouble *value)
+dia_unit_spinner_input (DiaUnitSpinner *self, double *value)
 {
-  gfloat val, factor = 1.0;
-  gchar *extra = NULL;
+  float val, factor = 1.0;
+  char *extra = NULL;
 
   val = g_strtod(gtk_entry_get_text(GTK_ENTRY(self)), &extra);
 
@@ -711,22 +711,19 @@ dia_toggle_button_swap_images(GtkToggleButton *widget,
   }
 }
 
+
 static void
-dia_toggle_button_destroy(GtkWidget *widget, gpointer data)
+dia_toggle_button_destroy (GtkWidget *widget, gpointer data)
 {
-  struct image_pair *images = (struct image_pair *)data;
+  struct image_pair *images = (struct image_pair *) data;
+
+  g_clear_object (&images->on);
+  g_clear_object (&images->off);
+  g_clear_pointer (&images, g_free);
 
-  if (images->on)
-    g_object_unref(images->on);
-  images->on = NULL;
-  if (images->off)
-    g_object_unref(images->off);
-  images->off = NULL;
-  if (images)
-    g_free(images);
-  images = NULL;
 }
 
+
 /** Create a toggle button given two image widgets for on and off */
 static GtkWidget *
 dia_toggle_button_new(GtkWidget *on_widget, GtkWidget *off_widget)
@@ -755,7 +752,7 @@ dia_toggle_button_new(GtkWidget *on_widget, GtkWidget *off_widget)
   rcstyle = gtk_rc_style_new ();
   rcstyle->xthickness = rcstyle->ythickness = 0;
   gtk_widget_modify_style (button, rcstyle);
-  g_object_unref (rcstyle);
+  g_clear_object (&rcstyle);
 
   gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
   /*  gtk_button_set_focus_on_click(GTK_BUTTON(button), FALSE);*/
@@ -779,7 +776,7 @@ dia_toggle_button_new(GtkWidget *on_widget, GtkWidget *off_widget)
 /* GTK3: This is built-in (new_from_resource, add_resource_path....) */
 /* Adapted from Gtk */
 GdkPixbuf *
-pixbuf_from_resource (const gchar *path)
+pixbuf_from_resource (const char *path)
 {
   GdkPixbufLoader *loader = NULL;
   GdkPixbuf *pixbuf = NULL;
@@ -806,15 +803,16 @@ pixbuf_from_resource (const gchar *path)
 
  out:
   gdk_pixbuf_loader_close (loader, NULL);
-  g_object_unref (loader);
+  g_clear_object (&loader);
   g_bytes_unref (bytes);
 
   return pixbuf;
 }
 
+
 GtkWidget *
-dia_toggle_button_new_with_icon_names (const gchar *on,
-                                       const gchar *off)
+dia_toggle_button_new_with_icon_names (const char *on,
+                                       const char *off)
 {
   GtkWidget *on_img, *off_img;
 
diff --git a/objects/AADL/aadlbox.c b/objects/AADL/aadlbox.c
index c507a230..67ecf5af 100644
--- a/objects/AADL/aadlbox.c
+++ b/objects/AADL/aadlbox.c
@@ -54,9 +54,9 @@ static void
 free_port(Aadlport *port)
 {
   if (port) {
-    g_free(port->handle);
-    g_free(port->declaration);
-    g_free(port);
+    g_clear_pointer (&port->handle, g_free);
+    g_clear_pointer (&port->declaration, g_free);
+    g_clear_pointer (&port, g_free);
   }
 }
 
@@ -242,13 +242,10 @@ aadlbox_change_free(struct PointChange *change)
 
     free_port (change->port);
     change->port = NULL;
+  } else if ((change->type==TYPE_ADD_CONNECTION && !change->applied) ||
+             (change->type==TYPE_REMOVE_CONNECTION && change->applied)) {
 
-  } else if ( (change->type==TYPE_ADD_CONNECTION && !change->applied) ||
-           (change->type==TYPE_REMOVE_CONNECTION && change->applied) ) {
-
-    g_free (change->connection);
-    change->connection = NULL;
-
+    g_clear_pointer (&change->connection, g_free);
   }
 }
 
diff --git a/objects/AADL/edit_port_declaration.c b/objects/AADL/edit_port_declaration.c
index 574d88ad..596c4a54 100644
--- a/objects/AADL/edit_port_declaration.c
+++ b/objects/AADL/edit_port_declaration.c
@@ -70,9 +70,9 @@ static void edit_port_declaration_revert
 static void edit_port_declaration_free (struct EditPortDeclarationChange *change)
 {
   if (change->applied)
-    g_free(change->oldvalue);
+    g_clear_pointer (&change->oldvalue, g_free);
   else
-    g_free(change->newvalue);
+    g_clear_pointer (&change->newvalue, g_free);
 }
 
 
diff --git a/objects/Database/compound.c b/objects/Database/compound.c
index e2dc6fea..9eda60f3 100644
--- a/objects/Database/compound.c
+++ b/objects/Database/compound.c
@@ -291,13 +291,15 @@ compound_state_set (CompoundState * state, Compound * comp)
   compound_sanity_check (comp, "Restored state");
 }
 
+
 static void
 compound_state_free (CompoundState * state)
 {
-  g_free (state->handle_states);
+  g_clear_pointer (&state->handle_states, g_free);
   g_free (state);
 }
 
+
 static CompoundChange *
 compound_change_new (Compound * comp, CompoundState * state)
 {
@@ -514,15 +516,17 @@ compound_save (Compound *comp, ObjectNode obj_node, DiaContext *ctx)
   data_add_color (attr, &comp->line_color, ctx);
 }
 
+
 static void
 compound_destroy (Compound * comp)
 {
   compound_sanity_check (comp, "Destroying");
 
   object_destroy (&comp->object);
-  g_free (comp->handles);
+  g_clear_pointer (&comp->handles, g_free);
 }
 
+
 static void
 compound_draw (Compound * comp, DiaRenderer * renderer)
 {
diff --git a/objects/Database/reference.c b/objects/Database/reference.c
index 7fc02966..225d2ef5 100644
--- a/objects/Database/reference.c
+++ b/objects/Database/reference.c
@@ -194,15 +194,17 @@ reference_create (Point *startpoint,
   return &ref->orth.object;
 }
 
+
 static void
 reference_destroy (TableReference * ref)
 {
   orthconn_destroy (&ref->orth);
 
-  g_free (ref->start_point_desc);
-  g_free (ref->end_point_desc);
+  g_clear_pointer (&ref->start_point_desc, g_free);
+  g_clear_pointer (&ref->end_point_desc, g_free);
 }
 
+
 static DiaObject *
 reference_load (ObjectNode obj_node, int version,DiaContext *ctx)
 {
diff --git a/objects/Database/table.c b/objects/Database/table.c
index fdb37cc3..9682ca71 100644
--- a/objects/Database/table.c
+++ b/objects/Database/table.c
@@ -89,19 +89,19 @@ static TableChange *table_change_new (Table *, TableState *,
                                       GList *, GList *, GList *);
 static void table_update_primary_key_font (Table *);
 
-static gchar * create_documentation_tag (gchar * comment,
-                                         gboolean tagging,
-                                         gint WrapPoint,
-                                         gint *NumberOfLines);
-static void draw_comments(DiaRenderer *renderer,
-                          DiaFont     *font,
-                          real         font_height,
-                          Color       *text_color,
-                          gchar       *comment,
-                          gboolean     comment_tagging,
-                          gint         Comment_line_length,
-                          Point       *p,
-                          gint         alignment);
+static char *create_documentation_tag (char     *comment,
+                                       gboolean  tagging,
+                                       int       WrapPoint,
+                                       int      *NumberOfLines);
+static void draw_comments (DiaRenderer *renderer,
+                           DiaFont     *font,
+                           double       font_height,
+                           Color       *text_color,
+                           char        *comment,
+                           gboolean     comment_tagging,
+                           int          Comment_line_length,
+                           Point       *p,
+                           int          alignment);
 
 /* ----------------------------------------------------------------------- */
 
@@ -324,6 +324,7 @@ table_attribute_ensure_connection_points (TableAttribute * attr,
   attr->right_connection->object = obj;
 }
 
+
 /**
  * Free a TableAttribute and its allocated resources. Upon return of
  * this function the passed pointer will not be valid anymore.
@@ -331,15 +332,16 @@ table_attribute_ensure_connection_points (TableAttribute * attr,
 static void
 table_attribute_free (TableAttribute * attr)
 {
-  if (attr->name) g_free (attr->name);
-  if (attr->type) g_free (attr->type);
-  if (attr->comment) g_free (attr->comment);
+  g_clear_pointer (&attr->name, g_free);
+  g_clear_pointer (&attr->type, g_free);
+  g_clear_pointer (&attr->comment, g_free);
 
   /* do not free the connection points here as they may be shared */
 
   g_free (attr);
 }
 
+
 /**
  * Create a copy of the passed attribute. The returned copy of the
  * attribute needs to be freed using g_free when it is no longer needed.
@@ -499,8 +501,8 @@ table_destroy (Table * table)
 
   element_destroy (&table->element);
 
-  g_free (table->name);
-  g_free (table->comment);
+  g_clear_pointer (&table->name, g_free);
+  g_clear_pointer (&table->comment, g_free);
 
   list = table->attributes;
   while (list != NULL) {
@@ -606,17 +608,17 @@ draw_comments (DiaRenderer *renderer,
                DiaFont     *font,
                real         font_height,
                Color       *text_color,
-               gchar       *comment,
+               char        *comment,
                gboolean     comment_tagging,
                gint         Comment_line_length,
                Point       *p,
-               gint         alignment)
+               int          alignment)
 {
-  gint      NumberOfLines = 0;
-  gint      Index;
-  gchar     *CommentString = 0;
-  gchar     *NewLineP= NULL;
-  gchar     *RenderP;
+  int   NumberOfLines = 0;
+  int   Index;
+  char *CommentString = 0;
+  char *NewLineP= NULL;
+  char *RenderP;
 
   CommentString =
     create_documentation_tag (comment, comment_tagging, Comment_line_length, &NumberOfLines);
@@ -634,9 +636,10 @@ draw_comments (DiaRenderer *renderer,
       break;
     }
   }
-  g_free (CommentString);
+  g_clear_pointer (&CommentString, g_free);
 }
 
+
 static void
 fill_diamond (DiaRenderer *renderer,
               real         half_height,
@@ -991,15 +994,15 @@ table_init_attributesbox_height (Table * table)
     if (table->visible_comment && IS_NOT_EMPTY(attrib->comment))
       {
         int num_of_lines = 0;
-        gchar * cmt_str = create_documentation_tag (attrib->comment,
-                                                    table->tagging_comment,
-                                                    TABLE_COMMENT_MAXWIDTH,
-                                                    &num_of_lines);
+        char * cmt_str = create_documentation_tag (attrib->comment,
+                                                   table->tagging_comment,
+                                                   TABLE_COMMENT_MAXWIDTH,
+                                                   &num_of_lines);
         width = dia_font_string_width (cmt_str,
                                        comment_font,
                                        comment_font_height);
         width += TABLE_ATTR_COMMENT_OFFSET;
-        g_free (cmt_str);
+        g_clear_pointer (&cmt_str, g_free);
 
         table->attributesbox_height += (comment_font_height * num_of_lines);
         table->attributesbox_height += comment_font_height / 2;
@@ -1084,26 +1087,26 @@ underline_table_attribute (DiaRenderer     *renderer,
  *      This function should most likely be move to a source file for
  *      handling global UML functionallity at some point.
  */
-static gchar *
-create_documentation_tag (gchar * comment,
-                          gboolean tagging,
-                          gint WrapPoint,
-                          gint *NumberOfLines)
+static char *
+create_documentation_tag (char     *comment,
+                          gboolean  tagging,
+                          int       WrapPoint,
+                          int      *NumberOfLines)
 {
-  gchar  *CommentTag           = tagging ? "{documentation = " : "";
-  gint   TagLength             = strlen(CommentTag);
+  char *CommentTag = tagging ? "{documentation = " : "";
+  int   TagLength  = strlen (CommentTag);
   /* Make sure that there is at least some value greater then zero for the WrapPoint to
    * support diagrams from earlier versions of Dia. So if the WrapPoint is zero then use
    * the taglength as the WrapPoint. If the Tag has been changed such that it has a length
    * of 0 then use 1.
    */
-  gint     WorkingWrapPoint = (TagLength<WrapPoint) ? WrapPoint : ((TagLength<=0)?1:TagLength);
-  gint     RawLength        = TagLength + strlen(comment) + (tagging?1:0);
-  gint     MaxCookedLength  = RawLength + RawLength/WorkingWrapPoint;
-  gchar    *WrappedComment  = g_malloc0(MaxCookedLength+1);
-  gint     AvailSpace       = WorkingWrapPoint - TagLength;
-  gchar    *Scan;
-  gchar    *BreakCandidate;
+  int   WorkingWrapPoint = (TagLength<WrapPoint) ? WrapPoint : ((TagLength<=0)?1:TagLength);
+  int   RawLength        = TagLength + strlen(comment) + (tagging?1:0);
+  int   MaxCookedLength  = RawLength + RawLength/WorkingWrapPoint;
+  char *WrappedComment   = g_malloc0(MaxCookedLength+1);
+  int   AvailSpace       = WorkingWrapPoint - TagLength;
+  char *Scan;
+  char *BreakCandidate;
   gunichar ScanChar;
   gboolean AddNL            = FALSE;
 
@@ -1149,6 +1152,7 @@ create_documentation_tag (gchar * comment,
   return WrappedComment;
 }
 
+
 /**
  * Compute the dimension of the box surrounding the table's name and its
  * comment if any and if it is visible, store it (the height) in the
@@ -1156,38 +1160,37 @@ create_documentation_tag (gchar * comment,
  * function makes use of the fonts defined in the passed table
  * structure, so be sure to initialize them before calling this routine.
  */
-static real
+static double
 table_calculate_namebox_data (Table * table)
 {
-  real maxwidth = 0.0;
+  double maxwidth = 0.0;
 
-  if (IS_NOT_EMPTY(table->name))
-    {
-      maxwidth = dia_font_string_width (table->name,
-                                        table->name_font,
-                                        table->name_font_height);
-    }
+  if (IS_NOT_EMPTY (table->name)) {
+    maxwidth = dia_font_string_width (table->name,
+                                      table->name_font,
+                                      table->name_font_height);
+  }
   table->namebox_height = table->name_font_height + 2*0.1;
 
-  if (table->visible_comment && IS_NOT_EMPTY(table->comment))
-    {
-      real width;
-      gint numOfCommentLines = 0;
-      gchar * wrapped_box = create_documentation_tag (table->comment,
-                                                      table->tagging_comment,
-                                                      TABLE_COMMENT_MAXWIDTH,
-                                                      &numOfCommentLines);
-      width = dia_font_string_width (wrapped_box,
-                                     table->comment_font,
-                                     table->comment_font_height);
-      g_free (wrapped_box);
-      table->namebox_height += table->comment_font_height * numOfCommentLines;
-      maxwidth = MAX(width, maxwidth);
-    }
+  if (table->visible_comment && IS_NOT_EMPTY (table->comment)) {
+    double width;
+    int numOfCommentLines = 0;
+    char * wrapped_box = create_documentation_tag (table->comment,
+                                                   table->tagging_comment,
+                                                   TABLE_COMMENT_MAXWIDTH,
+                                                   &numOfCommentLines);
+    width = dia_font_string_width (wrapped_box,
+                                   table->comment_font,
+                                   table->comment_font_height);
+    g_clear_pointer (&wrapped_box, g_free);
+    table->namebox_height += table->comment_font_height * numOfCommentLines;
+    maxwidth = MAX(width, maxwidth);
+  }
 
   return maxwidth;
 }
 
+
 static void
 table_update_positions (Table *table)
 {
@@ -1269,17 +1272,16 @@ table_update_positions (Table *table)
 
       y += attr_font_height;
 
-      if (table->visible_comment && IS_NOT_EMPTY(attr->comment))
-        {
-          gint num_of_lines = 0;
-          gchar * str = create_documentation_tag (attr->comment,
-                                                  table->tagging_comment,
-                                                  TABLE_COMMENT_MAXWIDTH,
-                                                  &num_of_lines);
-          y += table->comment_font_height * num_of_lines;
-          y += table->comment_font_height/2.0;
-          g_free (str);
-        }
+      if (table->visible_comment && IS_NOT_EMPTY (attr->comment)) {
+        int num_of_lines = 0;
+        char * str = create_documentation_tag (attr->comment,
+                                               table->tagging_comment,
+                                               TABLE_COMMENT_MAXWIDTH,
+                                               &num_of_lines);
+        y += table->comment_font_height * num_of_lines;
+        y += table->comment_font_height / 2.0;
+        g_clear_pointer (&str, g_free);
+      }
 
       list = g_list_next (list);
     }
@@ -1453,8 +1455,8 @@ table_state_free (TableState * state)
 {
   GList * list;
 
-  g_free (state->name);
-  g_free (state->comment);
+  g_clear_pointer (&state->name, g_free);
+  g_clear_pointer (&state->comment, g_free);
 
   list = state->attributes;
   while (list != NULL)
@@ -1511,7 +1513,7 @@ table_change_free (TableChange *change)
       ConnectionPoint * cp = (ConnectionPoint *) lst->data;
       g_assert (cp->connected == NULL);
       object_remove_connections_to (cp);
-      g_free (cp);
+      g_clear_pointer (&cp, g_free);
 
       lst = g_list_next (lst);
     }
diff --git a/objects/ER/attribute.c b/objects/ER/attribute.c
index e86f828b..4be561b3 100644
--- a/objects/ER/attribute.c
+++ b/objects/ER/attribute.c
@@ -458,7 +458,7 @@ static void
 attribute_destroy(Attribute *attribute)
 {
   element_destroy(&attribute->element);
-  g_free(attribute->name);
+  g_clear_pointer (&attribute->name, g_free);
 }
 
 static DiaObject *
diff --git a/objects/ER/entity.c b/objects/ER/entity.c
index cecc4829..7d3b9c59 100644
--- a/objects/ER/entity.c
+++ b/objects/ER/entity.c
@@ -419,14 +419,16 @@ entity_create(Point *startpoint,
   return &entity->element.object;
 }
 
+
 static void
 entity_destroy (Entity *entity)
 {
   g_clear_object (&entity->font);
   element_destroy (&entity->element);
-  g_free (entity->name);
+  g_clear_pointer (&entity->name, g_free);
 }
 
+
 static DiaObject *
 entity_copy(Entity *entity)
 {
diff --git a/objects/ER/participation.c b/objects/ER/participation.c
index f5ffded2..57aea80b 100644
--- a/objects/ER/participation.c
+++ b/objects/ER/participation.c
@@ -261,9 +261,9 @@ participation_draw (Participation *participation, DiaRenderer *renderer)
 
     dia_renderer_draw_polyline (renderer, left_points, n, &color_black);
     dia_renderer_draw_polyline (renderer, right_points, n, &color_black);
-    g_free (left_points);
-    g_free (right_points);
-  }  else {
+    g_clear_pointer (&left_points, g_free);
+    g_clear_pointer (&right_points, g_free);
+  } else {
     dia_renderer_draw_polyline (renderer, points, n, &color_black);
   }
 }
diff --git a/objects/ER/relationship.c b/objects/ER/relationship.c
index c35af14f..3f49ac1a 100644
--- a/objects/ER/relationship.c
+++ b/objects/ER/relationship.c
@@ -476,16 +476,18 @@ relationship_create(Point *startpoint,
   return &relationship->element.object;
 }
 
+
 static void
 relationship_destroy (Relationship *relationship)
 {
   g_clear_object (&relationship->font);
   element_destroy (&relationship->element);
-  g_free (relationship->name);
-  g_free (relationship->left_cardinality);
-  g_free (relationship->right_cardinality);
+  g_clear_pointer (&relationship->name, g_free);
+  g_clear_pointer (&relationship->left_cardinality, g_free);
+  g_clear_pointer (&relationship->right_cardinality, g_free);
 }
 
+
 static DiaObject *
 relationship_copy(Relationship *relationship)
 {
diff --git a/objects/FS/flow-ortho.c b/objects/FS/flow-ortho.c
index d9fc7a8b..97595dfa 100644
--- a/objects/FS/flow-ortho.c
+++ b/objects/FS/flow-ortho.c
@@ -225,7 +225,7 @@ orthflow_change_apply_revert(ObjectChange* objchg, DiaObject* obj)
   if ( change->change_type & TEXT_EDIT  || change->change_type == BOTH ) {
     char* tmp = text_get_string_copy( oflow->text ) ;
     text_set_string( oflow->text, change->text ) ;
-    g_free( change->text ) ;
+    g_clear_pointer (&change->text, g_free);
     change->text = tmp ;
   }
 }
@@ -236,7 +236,7 @@ orthflow_change_free(ObjectChange* objchg)
   struct _OrthflowChange* change = (struct _OrthflowChange*) objchg ;
 
   if (change->change_type & TEXT_EDIT  || change->change_type == BOTH ) {
-    g_free(change->text) ;
+    g_clear_pointer (&change->text, g_free) ;
   }
 }
 
diff --git a/objects/FS/function.c b/objects/FS/function.c
index b23d8f8c..cc021b6a 100644
--- a/objects/FS/function.c
+++ b/objects/FS/function.c
@@ -202,8 +202,8 @@ function_change_apply_revert( ObjectChange* objchg, DiaObject* obj)
   if ( change->change_type == TEXT_EDIT || change->change_type == ALL ) {
      ttxt = text_get_string_copy( fcn->text ) ;
      text_set_string( fcn->text, change->text ) ;
-     g_free( change->text ) ;
-     change->text = ttxt ;
+    g_clear_pointer (&change->text, g_free);
+    change->text = ttxt;
   }
 }
 
@@ -213,7 +213,7 @@ function_change_free( ObjectChange* objchg )
   FunctionChange* change = (FunctionChange*) objchg ;
 
   if ( change->change_type == TEXT_EDIT ) {
-     g_free( change->text ) ;
+    g_clear_pointer (&change->text, g_free);
   }
 }
 
@@ -596,8 +596,8 @@ function_insert_word( Function* func, const char* word, gboolean newline )
                        + ( newline ? 2 : 1) ) ;
   sprintf( new_chars, newline ? "%s\n%s" : "%s%s", old_chars, word ) ;
   text_set_string( func->text, new_chars ) ;
-  g_free( new_chars ) ;
-  g_free( old_chars ) ;
+  g_clear_pointer (&new_chars, g_free) ;
+  g_clear_pointer (&old_chars, g_free) ;
   function_update_data( func ) ;
   text_set_cursor_at_end( func->text ) ;
 
diff --git a/objects/GRAFCET/boolequation.c b/objects/GRAFCET/boolequation.c
index c2856c5a..33889158 100644
--- a/objects/GRAFCET/boolequation.c
+++ b/objects/GRAFCET/boolequation.c
@@ -44,13 +44,14 @@ typedef struct {
   BlockDestroyFunc destroy;
 } BlockOps;
 
+
 struct _Block {
   BlockType type;
   BlockOps *ops;
   Point bl, ur, pos;
   union {
     Block *inside; /* overline, parens */
-    const gchar *text;
+    char *text;
     GSList *contained;
     OperatorType operator;
   } d;
@@ -116,15 +117,19 @@ textblock_draw (Block *block, Boolequation *booleq, DiaRenderer *renderer)
                             &booleq->color);
 }
 
+
 static void
-textblock_destroy(Block *block)
+textblock_destroy (Block *block)
 {
   if (!block) return;
-  g_assert(block->type == BLOCK_TEXT);
-  g_free((void *)block->d.text);
-  g_free(block);
+
+  g_return_if_fail (block->type == BLOCK_TEXT);
+
+  g_clear_pointer (&block->d.text, g_free);
+  g_free (block);
 }
 
+
 static BlockOps text_block_ops = {
   textblock_get_boundingbox,
   textblock_draw,
@@ -215,13 +220,18 @@ opblock_draw (Block *block, Boolequation *booleq, DiaRenderer *renderer)
                             &booleq->color);
 }
 
-static void opblock_destroy(Block *block)
+
+static void
+opblock_destroy (Block *block)
 {
   if (!block) return;
-  g_assert(block->type == BLOCK_OPERATOR);
-  g_free(block);
+
+  g_return_if_fail (block->type == BLOCK_OPERATOR);
+
+  g_free (block);
 }
 
+
 static BlockOps operator_block_ops = {
   opblock_get_boundingbox,
   opblock_draw,
@@ -310,15 +320,20 @@ overlineblock_draw (Block *block, Boolequation *booleq, DiaRenderer *renderer)
   dia_renderer_draw_line (renderer,&ul,&ur,&booleq->color);
 }
 
+
 static void
-overlineblock_destroy(Block *block)
+overlineblock_destroy (Block *block)
 {
   if (!block) return;
-  g_assert(block->type == BLOCK_OVERLINE);
+
+  g_return_if_fail(block->type == BLOCK_OVERLINE);
+
   block->d.inside->ops->destroy(block->d.inside);
-  g_free(block);
+
+  g_free (block);
 }
 
+
 static BlockOps overline_block_ops = {
   overlineblock_get_boundingbox,
   overlineblock_draw,
@@ -382,15 +397,20 @@ parensblock_draw (Block *block, Boolequation *booleq, DiaRenderer *renderer)
   dia_renderer_draw_string (renderer,")",&pt,ALIGN_LEFT,&booleq->color);
 }
 
+
 static void
-parensblock_destroy(Block *block)
+parensblock_destroy (Block *block)
 {
   if (!block) return;
-  g_assert(block->type == BLOCK_PARENS);
-  block->d.inside->ops->destroy(block->d.inside);
-  g_free(block);
+
+  g_return_if_fail (block->type == BLOCK_PARENS);
+
+  block->d.inside->ops->destroy (block->d.inside);
+
+  g_free (block);
 }
 
+
 static BlockOps parens_block_ops = {
   parensblock_get_boundingbox,
   parensblock_draw,
@@ -485,7 +505,7 @@ compoundblock_destroy(Block *block)
   }
 
   g_slist_free(block->d.contained);
-  g_free(block);
+  g_clear_pointer (&block, g_free);
 }
 
 static BlockOps compound_block_ops = {
@@ -556,14 +576,17 @@ compoundblock_create(const gchar **str)
 
 /* Boolequation : */
 void
-boolequation_set_value(Boolequation *booleq, const gchar *value)
+boolequation_set_value (Boolequation *booleq, const char *value)
 {
-  g_return_if_fail(booleq);
-  if (booleq->value) g_free((gchar *)booleq->value);
-  if (booleq->rootblock) booleq->rootblock->ops->destroy(booleq->rootblock);
+  g_return_if_fail (booleq);
+  g_clear_pointer (&booleq->value, g_free);
 
-  booleq->value = g_strdup(value);
-  booleq->rootblock = compoundblock_create(&value);
+  if (booleq->rootblock) {
+    booleq->rootblock->ops->destroy (booleq->rootblock);
+  }
+
+  booleq->value = g_strdup (value);
+  booleq->rootblock = compoundblock_create (&value);
   /* a good bounding box recalc here would be nice. */
 }
 
@@ -585,16 +608,20 @@ boolequation_create (const gchar *value,
   return booleq;
 }
 
+
 void
 boolequation_destroy(Boolequation *booleq)
 {
-  g_return_if_fail(booleq);
+  g_return_if_fail (booleq);
   g_clear_object (&booleq->font);
-  if (booleq->value) g_free((gchar *)booleq->value);
-  if (booleq->rootblock) booleq->rootblock->ops->destroy(booleq->rootblock);
+  g_clear_pointer (&booleq->value, g_free);
+
+  if (booleq->rootblock) booleq->rootblock->ops->destroy (booleq->rootblock);
+
   g_free (booleq);
 }
 
+
 void
 save_boolequation(ObjectNode obj_node, const gchar *attrname,
                  Boolequation *booleq, DiaContext *ctx)
diff --git a/objects/GRAFCET/boolequation.h b/objects/GRAFCET/boolequation.h
index 61cbfdeb..42246dfb 100644
--- a/objects/GRAFCET/boolequation.h
+++ b/objects/GRAFCET/boolequation.h
@@ -39,7 +39,7 @@ typedef struct {
 
   Point pos;
 
-  const gchar *value;
+  char *value;
 
   Block *rootblock;
 
diff --git a/objects/GRAFCET/condition.c b/objects/GRAFCET/condition.c
index 33cc036c..424e0ed1 100644
--- a/objects/GRAFCET/condition.c
+++ b/objects/GRAFCET/condition.c
@@ -429,15 +429,17 @@ condition_create(Point *startpoint,
   return &condition->connection.object;
 }
 
+
 static void
-condition_destroy(Condition *condition)
+condition_destroy (Condition *condition)
 {
   g_clear_object (&condition->cond_font);
   boolequation_destroy (condition->cond);
-  g_free (condition->cond_value);
+  g_clear_pointer (&condition->cond_value, g_free);
   connection_destroy (&condition->connection);
 }
 
+
 static DiaObject *
 condition_load(ObjectNode obj_node, int version, DiaContext *ctx)
 {
diff --git a/objects/GRAFCET/step.c b/objects/GRAFCET/step.c
index 5967e9f0..d3ada10e 100644
--- a/objects/GRAFCET/step.c
+++ b/objects/GRAFCET/step.c
@@ -632,7 +632,7 @@ static void
 step_destroy (Step *step)
 {
   g_clear_object (&step->font);
-  g_free (step->id);
+  g_clear_pointer (&step->id, g_free);
   element_destroy (&step->element);
 }
 
diff --git a/objects/GRAFCET/transition.c b/objects/GRAFCET/transition.c
index 884d2c3a..de0f2893 100644
--- a/objects/GRAFCET/transition.c
+++ b/objects/GRAFCET/transition.c
@@ -488,7 +488,7 @@ transition_destroy (Transition *transition)
 {
   g_clear_object (&transition->rcep_font);
   boolequation_destroy (transition->receptivity);
-  g_free (transition->rcep_value);
+  g_clear_pointer (&transition->rcep_value, g_free);
   element_destroy (&transition->element);
 }
 
diff --git a/objects/Istar/link.c b/objects/Istar/link.c
index 4f1b5936..96868d64 100644
--- a/objects/Istar/link.c
+++ b/objects/Istar/link.c
@@ -455,7 +455,7 @@ link_draw (Link *link, DiaRenderer *renderer)
 {
   Point *endpoints, p1, p2, pa;
   Arrow arrow;
-  gchar *annot;
+  char *annot;
   double w;
   BezPoint bpl[4];
 
@@ -520,7 +520,7 @@ link_draw (Link *link, DiaRenderer *renderer)
   if ((annot != NULL) && strlen (annot) != 0) {
     dia_renderer_draw_string (renderer, annot, &pa, ALIGN_CENTER, &color_black);
   }
-  if (annot!=NULL) g_free(annot);
+  g_clear_pointer (&annot, g_free);
 
   /** special stuff for dependency **/
   if (link->type == DEPENDENCY) {
diff --git a/objects/Jackson/phenomenon.c b/objects/Jackson/phenomenon.c
index e6426c97..942fbdf1 100644
--- a/objects/Jackson/phenomenon.c
+++ b/objects/Jackson/phenomenon.c
@@ -56,7 +56,7 @@ struct _Message {
 
   Handle text_handle;
 
-  gchar *text;
+  char *text;
   Point text_pos;
   real text_width;
 
@@ -259,7 +259,7 @@ message_draw (Message *message, DiaRenderer *renderer)
   Point *endpoints, p1, p2;
   Arrow arrow;
   int n1 = 1, n2 = 0;
-  gchar *mname = g_strdup (message->text);
+  char *mname = g_strdup (message->text);
 
   /* some asserts */
   assert(message != NULL);
@@ -302,7 +302,7 @@ message_draw (Message *message, DiaRenderer *renderer)
     dia_renderer_draw_string (renderer, mname, &message->text_pos, ALIGN_CENTER, &color_black);
   }
 
-  if (mname) g_free (mname);
+  g_clear_pointer (&mname, g_free);
 }
 
 /* creation here */
@@ -372,7 +372,7 @@ message_destroy(Message *message)
 {
   connection_destroy(&message->connection);
 
-  g_free(message->text);
+  g_clear_pointer (&message->text, g_free);
 }
 
 static void
diff --git a/objects/KAOS/metaandorrel.c b/objects/KAOS/metaandorrel.c
index 905fc6ad..78475a89 100644
--- a/objects/KAOS/metaandorrel.c
+++ b/objects/KAOS/metaandorrel.c
@@ -62,7 +62,7 @@ struct _Maor {
 
   Handle text_handle;
 
-  gchar *text;
+  char *text;
   Point text_pos;
   real text_width;
 
@@ -426,7 +426,7 @@ maor_draw (Maor *maor, DiaRenderer *renderer)
   Arrow arrow;
   BezPoint bpl[6];
   Point pl[7];
-  gchar *mname = g_strdup(maor->text);
+  char *mname = g_strdup (maor->text);
 
   /* some asserts */
   assert(maor != NULL);
@@ -493,9 +493,7 @@ maor_draw (Maor *maor, DiaRenderer *renderer)
                               &color_black);
   }
 
-  if (mname) {
-    g_free (mname);
-  }
+  g_clear_pointer (&mname, g_free);
 }
 
 
@@ -576,7 +574,7 @@ maor_destroy(Maor *maor)
 {
   connection_destroy(&maor->connection);
 
-  g_free(maor->text);
+  g_clear_pointer (&maor->text, g_free);
 }
 
 static void
diff --git a/objects/KAOS/metabinrel.c b/objects/KAOS/metabinrel.c
index f396f291..0a1f5579 100644
--- a/objects/KAOS/metabinrel.c
+++ b/objects/KAOS/metabinrel.c
@@ -332,10 +332,10 @@ compute_line(Point* p1, Point* p2, Point *pm, BezPoint* line) {
 }
 
 
-static gchar *
+static char *
 compute_text (Mbr *mbr)
 {
-  gchar* annot;
+  char *annot;
   switch (mbr->type) {
     case MBR_RESP:
       annot = g_strdup ("Resp");
@@ -369,6 +369,7 @@ compute_text (Mbr *mbr)
   return annot;
 }
 
+
 /* drawing here -- TBD inverse flow ??  */
 static void
 mbr_draw (Mbr *mbr, DiaRenderer *renderer)
@@ -377,7 +378,7 @@ mbr_draw (Mbr *mbr, DiaRenderer *renderer)
   Point p1,p2,pm1,pm2;
   Point pa1,pa2;
   Arrow arrow;
-  gchar *annot;
+  char *annot;
   double k,dx,dy,dxn,dyn,dxp,dyp;
 
   /* some asserts */
@@ -464,7 +465,7 @@ mbr_draw (Mbr *mbr, DiaRenderer *renderer)
     dia_renderer_draw_string (renderer,annot,&mbr->pm,ALIGN_CENTER,&MBR_FG_COLOR);
   }
 
-  g_free (annot);
+  g_clear_pointer (&annot, g_free);
 }
 
 /* creation here */
@@ -552,7 +553,7 @@ mbr_update_data(Mbr *mbr)
   DiaRectangle rect;
   Point p1,p2;
   Point p3,p4;
-  gchar *text;
+  char *text;
 
 /* Too complex to easily decide -- this is essentially a bezier curve */
 /*
@@ -598,7 +599,7 @@ mbr_update_data(Mbr *mbr)
   rect.bottom = rect.top + MBR_DECFONTHEIGHT;
   rectangle_union(&obj->bounding_box, &rect);
 
-  g_free(text);   /* free auxilliary text */
+  g_clear_pointer (&text, g_free);   /* free auxilliary text */
 }
 
 static DiaObject *
diff --git a/objects/Misc/diagram_as_object.c b/objects/Misc/diagram_as_object.c
index 3dac4ee6..18aa2d4b 100644
--- a/objects/Misc/diagram_as_object.c
+++ b/objects/Misc/diagram_as_object.c
@@ -59,7 +59,7 @@ typedef struct _DiagramAsElement {
   Color inner_color;
   gboolean show_background;
 
-  gchar *filename;
+  char *filename;
   time_t mtime;
   DiagramData *data;
 
@@ -100,7 +100,7 @@ DiaObjectType diagram_as_element_type =
 
 static void _dae_update_data (DiagramAsElement *dae);
 
-static const gchar *_extensions[] = { "dia", NULL };
+static const char *_extensions[] = { "dia", NULL };
 
 static PropDescription _dae_props[] = {
   ELEMENT_COMMON_PROPERTIES,
@@ -203,8 +203,8 @@ _dae_draw (DiagramAsElement *dae, DiaRenderer *renderer)
     } else {
       /* we have to render to an image and draw that */
       if (!dae->image) { /* lazy creation */
-        gchar *imgfname = NULL;
-        gint fd = g_file_open_tmp ("diagram-as-elementXXXXXX.png", &imgfname, NULL);
+        char *imgfname = NULL;
+        int fd = g_file_open_tmp ("diagram-as-elementXXXXXX.png", &imgfname, NULL);
         if (fd != -1) {
           DiaExportFilter *ef = filter_export_get_by_name ("cairo-alpha-png");
           if (!ef) { /* prefer cairo with alpha, but don't require it */
@@ -221,14 +221,14 @@ _dae_draw (DiagramAsElement *dae, DiaRenderer *renderer)
               /* some extra gymnastics to create an image w/o filename */
               if (tmp_image) {
                 dae->image = dia_image_new_from_pixbuf ((GdkPixbuf *) dia_image_pixbuf (tmp_image));
-                g_object_unref (tmp_image);
+                g_clear_object (&tmp_image);
               }
               /* FIXME: where to put the message in case of an error? */
               dia_context_release (ctx);
             }
           } /* found a filter */
           g_unlink (imgfname);
-          g_free (imgfname);
+          g_clear_pointer (&imgfname, g_free);
         } /* temporary file created*/
       } /* only if we have no image yet */
       if (dae->image) {
@@ -259,8 +259,7 @@ _dae_update_data(DiagramAsElement *dae)
       && dae->mtime != statbuf.st_mtime) {
     DiaImportFilter *inf;
 
-    if (dae->data)
-      g_object_unref(dae->data);
+    g_clear_object (&dae->data);
     dae->data = g_object_new (DIA_TYPE_DIAGRAM_DATA, NULL);
 
     inf = filter_guess_import_filter(dae->filename);
@@ -278,10 +277,7 @@ _dae_update_data(DiagramAsElement *dae)
       dia_context_release (ctx);
     }
     /* invalidate possibly cached image */
-    if (dae->image) {
-      g_object_unref (dae->image);
-      dae->image = NULL;
-    }
+    g_clear_object (&dae->image);
   }
   /* fixme - fit the scale to draw the diagram in elements size ?*/
   if (dae->scale)
@@ -297,20 +293,21 @@ _dae_update_data(DiagramAsElement *dae)
 
   --working;
 }
+
+
 static void
 _dae_destroy(DiagramAsElement *dae)
 {
-  if (dae->data)
-    g_object_unref(dae->data);
+  g_clear_object (&dae->data);
 
-  g_free(dae->filename);
+  g_clear_pointer (&dae->filename, g_free);
 
-  if (dae->image)
-    g_object_unref (dae->image);
+  g_clear_object (&dae->image);
 
   element_destroy(&dae->element);
 }
 
+
 static ObjectOps _dae_ops = {
   (DestroyFunc)         _dae_destroy,
   (DrawFunc)            _dae_draw,
@@ -381,11 +378,11 @@ _dae_load (ObjectNode obj_node, int version, DiaContext *ctx)
   /* filename de-normalization */
   dae = (DiagramAsElement*)obj;
   if (strlen(dae->filename) && !g_path_is_absolute (dae->filename)) {
-    gchar *dirname = g_path_get_dirname (dia_context_get_filename(ctx));
-    gchar *fname = g_build_filename (dirname, dae->filename, NULL);
-    g_free (dae->filename);
+    char *dirname = g_path_get_dirname (dia_context_get_filename(ctx));
+    char *fname = g_build_filename (dirname, dae->filename, NULL);
+    g_clear_pointer (&dae->filename, g_free);
     dae->filename = fname;
-    g_free (dirname);
+    g_clear_pointer (&dirname, g_free);
 
     /* need to update again with new filenames */
     _dae_update_data(dae);
@@ -393,21 +390,22 @@ _dae_load (ObjectNode obj_node, int version, DiaContext *ctx)
   return obj;
 }
 
+
 static void
 _dae_save (DiaObject *obj, ObjectNode obj_node, DiaContext *ctx)
 {
   DiagramAsElement *dae;
   /* filename normalization */
-  gchar *saved_path = NULL;
+  char *saved_path = NULL;
 
   dae = (DiagramAsElement*)obj;
   if (strlen(dae->filename) && g_path_is_absolute (dae->filename)) {
-    gchar *dirname = g_path_get_dirname (dia_context_get_filename (ctx));
+    char *dirname = g_path_get_dirname (dia_context_get_filename (ctx));
     if (strstr (dae->filename, dirname) == dae->filename) {
       saved_path = dae->filename;
       dae->filename += (strlen (dirname) + g_str_has_suffix (dirname, G_DIR_SEPARATOR_S) ? 0 : 1);
     }
-    g_free (dirname);
+    g_clear_pointer (&dirname, g_free);
   }
   object_save_using_properties (obj, obj_node, ctx);
 
diff --git a/objects/Misc/grid_object.c b/objects/Misc/grid_object.c
index 58b87282..ac2bc99c 100644
--- a/objects/Misc/grid_object.c
+++ b/objects/Misc/grid_object.c
@@ -498,7 +498,7 @@ grid_object_reallocate_cells (Grid_Object* grid_object)
       }
     }
 
-  g_free(grid_object->cells);
+  g_clear_pointer (&grid_object->cells, g_free);
   grid_object->cells = new_cells;
   grid_object->cells_rows = new_rows;
   grid_object->cells_cols = new_cols;
@@ -508,7 +508,7 @@ static void
 grid_object_destroy(Grid_Object *grid_object)
 {
   element_destroy(&grid_object->element);
-  g_free(grid_object->cells);
+  g_clear_pointer (&grid_object->cells, g_free);
 }
 
 static DiaObject *
diff --git a/objects/Misc/measure.c b/objects/Misc/measure.c
index 37d68938..56f1a77d 100644
--- a/objects/Misc/measure.c
+++ b/objects/Misc/measure.c
@@ -226,7 +226,7 @@ measure_update_data (Measure *measure)
   extra->start_long  =
   extra->end_long    = (measure->line_width / 2.0);
 
-  g_free (measure->name);
+  g_clear_pointer (&measure->name, g_free);
   value = distance_point_point (&ends[0], &ends[1]);
   value *= measure->scale;
   value *= (28.346457 / units[measure->unit].factor);
diff --git a/objects/Misc/n_gon.c b/objects/Misc/n_gon.c
index d107f7ba..777aecb8 100644
--- a/objects/Misc/n_gon.c
+++ b/objects/Misc/n_gon.c
@@ -339,7 +339,7 @@ _ngon_make_name (Ngon *ng)
   const char *name = NULL;
   int i = 0;
 
-  g_free (ng->name);
+  g_clear_pointer (&ng->name, g_free);
   for (i = 0; i < G_N_ELEMENTS(_keys); ++i) {
     if (_keys[i].v == ng->num_rays) {
       if (ng->kind == NGON_CONVEX)
@@ -489,15 +489,18 @@ _ngon_update_data (Ngon *ng)
   element_update_handles(elem);
 
 }
+
+
 static void
 _ngon_destroy(Ngon *ng)
 {
   g_array_free (ng->points, TRUE);
-  if (ng->pattern)
-    g_object_unref (ng->pattern);
-  g_free (ng->name);
+  g_clear_object (&ng->pattern);
+  g_clear_pointer (&ng->name, g_free);
   element_destroy(&ng->element);
 }
+
+
 static DiaObject *
 _ngon_copy(Ngon *from)
 {
diff --git a/objects/Misc/tree.c b/objects/Misc/tree.c
index 1c144de3..dd961274 100644
--- a/objects/Misc/tree.c
+++ b/objects/Misc/tree.c
@@ -373,17 +373,19 @@ tree_create(Point *startpoint,
   return &tree->connection.object;
 }
 
+
 static void
-tree_destroy(Tree *tree)
+tree_destroy (Tree *tree)
 {
-  int i;
-  connection_destroy(&tree->connection);
-  for (i=0;i<tree->num_handles;i++)
-    g_free(tree->handles[i]);
-  g_free(tree->handles);
-  g_free(tree->parallel_points);
+  connection_destroy (&tree->connection);
+  for (int i = 0; i < tree->num_handles; i++) {
+    g_clear_pointer (&tree->handles[i], g_free);
+  }
+  g_clear_pointer (&tree->handles, g_free);
+  g_clear_pointer (&tree->parallel_points, g_free);
 }
 
+
 static DiaObject *
 tree_copy(Tree *tree)
 {
@@ -695,9 +697,7 @@ tree_change_free(struct PointChange *change)
 {
   if ( (change->type==TYPE_ADD_POINT && !change->applied) ||
        (change->type==TYPE_REMOVE_POINT && change->applied) ){
-    if (change->handle)
-      g_free(change->handle);
-    change->handle = NULL;
+    g_clear_pointer (&change->handle, g_free);
   }
 }
 
diff --git a/objects/SADT/box.c b/objects/SADT/box.c
index e77c455c..bf5c7a67 100644
--- a/objects/SADT/box.c
+++ b/objects/SADT/box.c
@@ -576,7 +576,7 @@ sadtbox_destroy(Box *box)
   connpointline_destroy(box->west);
   connpointline_destroy(box->north);
 
-  g_free(box->id);
+  g_clear_pointer (&box->id, g_free);
 
   element_destroy(&box->element);
 }
diff --git a/objects/UML/association.c b/objects/UML/association.c
index a8e1c93e..91862c4b 100644
--- a/objects/UML/association.c
+++ b/objects/UML/association.c
@@ -86,14 +86,14 @@ typedef enum {
 } AggregateType;
 
 typedef struct _AssociationEnd {
-  gchar *role; /* Can be NULL */
-  gchar *multiplicity; /* Can be NULL */
+  char *role; /* Can be NULL */
+  char *multiplicity; /* Can be NULL */
   Point text_pos;
-  real text_width;
-  real role_ascent;
-  real role_descent;
-  real multi_ascent;
-  real multi_descent;
+  double text_width;
+  double role_ascent;
+  double role_descent;
+  double multi_ascent;
+  double multi_descent;
   Alignment text_align;
   UMLVisibility visibility;    /* This value is only relevant if role is not null */
 
@@ -104,12 +104,12 @@ typedef struct _AssociationEnd {
 struct _AssociationState {
   ObjectState obj_state;
 
-  gchar *name;
+  char *name;
   AssociationDirection direction;
 
   struct {
-    gchar *role;
-    gchar *multiplicity;
+    char *role;
+    char *multiplicity;
     UMLVisibility visibility;  /* This value is only relevant if role is not null */
 
     int arrow;
@@ -123,11 +123,11 @@ struct _Association {
 
   Point text_pos;
   Alignment text_align;
-  real text_width;
-  real ascent;
-  real descent;
+  double text_width;
+  double ascent;
+  double descent;
 
-  gchar *name;
+  char *name;
   AssociationDirection direction;
   AggregateType assoc_type;
 
@@ -139,8 +139,8 @@ struct _Association {
   Color line_color;
 
   DiaFont *font;
-  real     font_height;
-  real     line_width;
+  double   font_height;
+  double   line_width;
 };
 
 #define ASSOCIATION_TRIANGLESIZE (assoc->font_height)
@@ -477,13 +477,13 @@ association_draw (Association *assoc, DiaRenderer *renderer)
     pos = end->text_pos;
 
     if (end->role != NULL && *end->role) {
-      gchar *role_name = g_strdup_printf ("%c%s", visible_char[(int) end->visibility], end->role);
+      char *role_name = g_strdup_printf ("%c%s", visible_char[(int) end->visibility], end->role);
       dia_renderer_draw_string (renderer,
                                 role_name,
                                 &pos,
                                 end->text_align,
                                 &assoc->text_color);
-      g_free (role_name);
+      g_clear_pointer (&role_name, g_free);
       pos.y += assoc->font_height;
     }
     if (end->multiplicity != NULL) {
@@ -496,19 +496,21 @@ association_draw (Association *assoc, DiaRenderer *renderer)
   }
 }
 
+
 static void
-association_state_free(ObjectState *ostate)
+association_state_free (ObjectState *ostate)
 {
-  AssociationState *state = (AssociationState *)ostate;
-  int i;
-  g_free(state->name);
+  AssociationState *state = (AssociationState *) ostate;
 
-  for (i=0;i<2;i++) {
-    g_free(state->end[i].role);
-    g_free(state->end[i].multiplicity);
+  g_clear_pointer (&state->name, g_free);
+
+  for (int i = 0; i < 2; i++) {
+    g_clear_pointer (&state->end[i].role, g_free);
+    g_clear_pointer (&state->end[i].multiplicity, g_free);
   }
 }
 
+
 static AssociationState *
 association_get_state(Association *assoc)
 {
@@ -540,7 +542,7 @@ association_set_state(Association *assoc, AssociationState *state)
   int i;
   AssociationEnd *end;
 
-  g_free(assoc->name);
+  g_clear_pointer (&assoc->name, g_free);
   assoc->name = state->name;
   assoc->text_width = 0.0;
   assoc->ascent = 0.0;
@@ -558,8 +560,8 @@ association_set_state(Association *assoc, AssociationState *state)
 
   for (i=0;i<2;i++) {
     end = &assoc->end[i];
-    g_free(end->role);
-    g_free(end->multiplicity);
+    g_clear_pointer (&end->role, g_free);
+    g_clear_pointer (&end->multiplicity, g_free);
     end->role = state->end[i].role;
     end->multiplicity = state->end[i].multiplicity;
     end->arrow = state->end[i].arrow;
@@ -591,7 +593,7 @@ association_set_state(Association *assoc, AssociationState *state)
     }
   }
 
-  g_free(state);
+  g_clear_pointer (&state, g_free);
 
   association_update_data(assoc);
 }
@@ -925,15 +927,13 @@ association_get_object_menu (Association *assoc, Point *clickedpoint)
 static void
 association_destroy (Association *assoc)
 {
-  int i;
-
   orthconn_destroy (&assoc->orth);
   g_clear_object (&assoc->font);
-  g_free (assoc->name);
+  g_clear_pointer (&assoc->name, g_free);
 
-  for (i = 0; i < 2; i++) {
-    g_free (assoc->end[i].role);
-    g_free (assoc->end[i].multiplicity);
+  for (int i = 0; i < 2; i++) {
+    g_clear_pointer (&assoc->end[i].role, g_free);
+    g_clear_pointer (&assoc->end[i].multiplicity, g_free);
   }
 }
 
@@ -1008,17 +1008,17 @@ association_load (ObjectNode obj_node, int version, DiaContext *ctx)
 
     attr = object_find_attribute (obj_node, "ends");
     composite = attribute_first_data (attr);
-    for (i = 0; i < 2; i++) {
 
+    for (i = 0; i < 2; i++) {
       assoc->end[i].role = NULL;
       attr = composite_find_attribute (composite, "role");
       if (attr != NULL) {
         assoc->end[i].role = data_string (attribute_first_data (attr), ctx);
       }
+
       if (   assoc->end[i].role != NULL
           && 0 == strcmp (assoc->end[i].role, "")) {
-        g_free (assoc->end[i].role);
-        assoc->end[i].role = NULL;
+        g_clear_pointer (&assoc->end[i].role, g_free);
       }
 
       assoc->end[i].multiplicity = NULL;
@@ -1027,10 +1027,10 @@ association_load (ObjectNode obj_node, int version, DiaContext *ctx)
         assoc->end[i].multiplicity = data_string (attribute_first_data (attr),
                                                   ctx);
       }
+
       if (   assoc->end[i].multiplicity != NULL
           && 0 == strcmp (assoc->end[i].multiplicity, "")) {
-        g_free (assoc->end[i].multiplicity);
-        assoc->end[i].multiplicity = NULL;
+        g_clear_pointer (&assoc->end[i].multiplicity, g_free);
       }
 
       assoc->end[i].arrow = FALSE;
diff --git a/objects/UML/class.c b/objects/UML/class.c
index 4a0bb4e9..dcd86be7 100644
--- a/objects/UML/class.c
+++ b/objects/UML/class.c
@@ -378,15 +378,18 @@ _comment_get_state (DiaObject *obj)
   state->visible_comments = ((UMLClass *)obj)->visible_comments;
   return (ObjectState *)state;
 }
+
+
 static void
 _comment_set_state (DiaObject *obj, ObjectState *state)
 {
-  ((UMLClass *)obj)->visible_comments = ((CommentState *)state)->visible_comments;
+  ((UMLClass *) obj)->visible_comments = ((CommentState *) state)->visible_comments;
   g_free (state); /* rather strange convention set_state consumes the state */
-  umlclass_calculate_data((UMLClass *)obj);
-  umlclass_update_data((UMLClass *)obj);
+  umlclass_calculate_data ((UMLClass *)obj);
+  umlclass_update_data ((UMLClass *)obj);
 }
 
+
 static ObjectChange *
 umlclass_show_comments_callback(DiaObject *obj, Point *pos, gpointer data)
 {
@@ -574,9 +577,9 @@ uml_underline_text (DiaRenderer  *renderer,
                     real          line_width,
                     real          underline_width)
 {
-  Point    UnderlineStartPoint;
-  Point    UnderlineEndPoint;
-  gchar *whitespaces;
+  Point UnderlineStartPoint;
+  Point UnderlineEndPoint;
+  char *whitespaces;
   int first_non_whitespace = 0;
 
   UnderlineStartPoint = StartPoint;
@@ -592,7 +595,7 @@ uml_underline_text (DiaRenderer  *renderer,
   whitespaces = g_strdup (string);
   whitespaces[first_non_whitespace] = '\0';
   UnderlineStartPoint.x += dia_font_string_width (whitespaces, font, font_height);
-  g_free(whitespaces);
+  g_clear_pointer (&whitespaces, g_free);
   UnderlineEndPoint.x += dia_font_string_width (string, font, font_height);
   dia_renderer_set_linewidth (renderer, underline_width);
   dia_renderer_draw_line (renderer, &UnderlineStartPoint, &UnderlineEndPoint, color);
@@ -753,7 +756,7 @@ uml_draw_comments (DiaRenderer *renderer,
     }
   }
   p->y += font_height - ascent;
-  g_free (CommentString);
+  g_clear_pointer (&CommentString, g_free);
 }
 
 
@@ -944,7 +947,7 @@ umlclass_draw_attributebox (UMLClass    *umlclass,
       }
       list = g_list_next (list);
       i++;
-      g_free (attstr);
+      g_clear_pointer (&attstr, g_free);
     }
   }
   return Yoffset;
@@ -1112,11 +1115,9 @@ umlclass_draw_operationbox (UMLClass    *umlclass,
 
       list = g_list_next (list);
       i++;
-      g_free (opstr);
-    }
-    if (part_opstr) {
-      g_free (part_opstr);
+      g_clear_pointer (&opstr, g_free);
     }
+    g_clear_pointer (&part_opstr, g_free);
   }
   return Yoffset;
 }
@@ -1144,12 +1145,12 @@ umlclass_draw_template_parameters_box (UMLClass    *umlclass,
   Point TextInsert;
   GList *list;
   gint   i;
-  DiaFont   *font = umlclass->normal_font;
-  real       font_height = umlclass->font_height;
-  real       ascent;
-  Color     *fill_color = &umlclass->fill_color;
-  Color     *line_color = &umlclass->line_color;
-  Color     *text_color = &umlclass->text_color;
+  DiaFont *font = umlclass->normal_font;
+  real     font_height = umlclass->font_height;
+  real     ascent;
+  Color   *fill_color = &umlclass->fill_color;
+  Color   *line_color = &umlclass->line_color;
+  Color   *text_color = &umlclass->text_color;
 
 
   /*
@@ -1180,10 +1181,11 @@ umlclass_draw_template_parameters_box (UMLClass    *umlclass,
 
     list = g_list_next (list);
     i++;
-    g_free (paramstr);
+    g_clear_pointer (&paramstr, g_free);
   }
 }
 
+
 /**
  * Draw the class icon for the specified UMLClass object.
  * Set the renderer to the correct fill and line styles and the appropriate
@@ -1195,15 +1197,14 @@ umlclass_draw_template_parameters_box (UMLClass    *umlclass,
  * @param   DiaRenderer  renderer used to draw the object
  *
  */
-
 static void
 umlclass_draw (UMLClass *umlclass, DiaRenderer *renderer)
 {
-  real     y  = 0.0;
+  double y = 0.0;
   Element *elem;
 
-  assert(umlclass != NULL);
-  assert(renderer != NULL);
+  g_return_if_fail (umlclass != NULL);
+  g_return_if_fail (renderer != NULL);
 
   dia_renderer_set_fillstyle (renderer, FILLSTYLE_SOLID);
   dia_renderer_set_linewidth (renderer, umlclass->line_width);
@@ -1313,12 +1314,12 @@ umlclass_update_data(UMLClass *umlclass)
 
     y += umlclass->font_height;
     if (umlclass->visible_comments && attr->comment != NULL && attr->comment[0] != '\0') {
-      gint NumberOfLines = 0;
-      gchar *CommentString = 0;
+      int NumberOfLines = 0;
+      char *CommentString = 0;
 
       CommentString =
-        uml_create_documentation_tag(attr->comment, umlclass->comment_tagging, 
umlclass->comment_line_length, &NumberOfLines);
-      g_free(CommentString);
+        uml_create_documentation_tag (attr->comment, umlclass->comment_tagging, 
umlclass->comment_line_length, &NumberOfLines);
+      g_clear_pointer (&CommentString, g_free);
       y += umlclass->comment_font_height*NumberOfLines + umlclass->comment_font_height/2;
     }
 
@@ -1348,12 +1349,12 @@ umlclass_update_data(UMLClass *umlclass)
       y += umlclass->font_height;
     }
     if (umlclass->visible_comments && op->comment != NULL && op->comment[0] != '\0') {
-      gint NumberOfLines = 0;
-      gchar *CommentString = 0;
+      int NumberOfLines = 0;
+      char *CommentString = 0;
 
       CommentString =
         uml_create_documentation_tag(op->comment, umlclass->comment_tagging, umlclass->comment_line_length, 
&NumberOfLines);
-      g_free(CommentString);
+      g_clear_pointer (&CommentString, g_free);
       y += umlclass->comment_font_height*NumberOfLines + umlclass->comment_font_height/2;
     }
     list = g_list_next(list);
@@ -1409,9 +1410,8 @@ umlclass_calculate_name_data(UMLClass *umlclass)
   }
 
   umlclass->namebox_height = umlclass->classname_font_height + 4*0.1;
-  if (umlclass->stereotype_string != NULL) {
-    g_free(umlclass->stereotype_string);
-  }
+  g_clear_pointer (&umlclass->stereotype_string, g_free);
+
   if (umlclass->stereotype != NULL && umlclass->stereotype[0] != '\0') {
     umlclass->namebox_height += umlclass->font_height;
     umlclass->stereotype_string = g_strconcat ( UML_STEREOTYPE_START,
@@ -1435,12 +1435,12 @@ umlclass_calculate_name_data(UMLClass *umlclass)
                                                          umlclass->comment_line_length,
                                                          &NumberOfLines);
     width = dia_font_string_width (CommentString,
-                                    umlclass->comment_font,
-                                    umlclass->comment_font_height);
+                                   umlclass->comment_font,
+                                   umlclass->comment_font_height);
 
-    g_free(CommentString);
+    g_clear_pointer (&CommentString, g_free);
     umlclass->namebox_height += umlclass->comment_font_height * NumberOfLines;
-    maxwidth = MAX(width, maxwidth);
+    maxwidth = MAX (width, maxwidth);
   }
   return maxwidth;
 }
@@ -1490,21 +1490,21 @@ umlclass_calculate_attribute_data(UMLClass *umlclass)
       if (umlclass->visible_comments && attr->comment != NULL && attr->comment[0] != '\0')
       {
         int NumberOfLines = 0;
-        gchar *CommentString = uml_create_documentation_tag(attr->comment,
+        char *CommentString = uml_create_documentation_tag (attr->comment,
                                                             umlclass->comment_tagging,
                                                             umlclass->comment_line_length,
                                                             &NumberOfLines);
         width = dia_font_string_width(CommentString,
                                        umlclass->comment_font,
                                        umlclass->comment_font_height);
-        g_free(CommentString);
+        g_clear_pointer (&CommentString, g_free);
         umlclass->attributesbox_height += umlclass->comment_font_height * NumberOfLines + 
umlclass->comment_font_height/2;
         maxwidth = MAX(width, maxwidth);
       }
 
       i++;
       list = g_list_next(list);
-      g_free (attstr);
+      g_clear_pointer (&attstr, g_free);
     }
   }
 
@@ -1669,21 +1669,21 @@ umlclass_calculate_operation_data(UMLClass *umlclass)
 
       if (umlclass->visible_comments && op->comment != NULL && op->comment[0] != '\0'){
         int NumberOfLines = 0;
-        gchar *CommentString = uml_create_documentation_tag(op->comment,
+        char *CommentString = uml_create_documentation_tag (op->comment,
                                                             umlclass->comment_tagging,
                                                             umlclass->comment_line_length,
                                                             &NumberOfLines);
         width = dia_font_string_width(CommentString,
                                        umlclass->comment_font,
                                        umlclass->comment_font_height);
-        g_free(CommentString);
+        g_clear_pointer (&CommentString, g_free);
         umlclass->operationsbox_height += umlclass->comment_font_height * NumberOfLines + 
umlclass->comment_font_height/2;
         maxwidth = MAX(width, maxwidth);
       }
 
       i++;
       list = g_list_next(list);
-      g_free (opstr);
+      g_clear_pointer (&opstr, g_free);
     }
   }
 
@@ -1769,7 +1769,7 @@ umlclass_calculate_data(UMLClass *umlclass)
 
         i++;
         list = g_list_next(list);
-       g_free (paramstr);
+        g_clear_pointer (&paramstr, g_free);
       }
     }
     umlclass->templates_width = maxwidth + 2*0.2;
@@ -1949,15 +1949,15 @@ umlclass_destroy(UMLClass *umlclass)
 
   element_destroy (&umlclass->element);
 
-  g_free(umlclass->name);
-  g_free(umlclass->stereotype);
-  g_free(umlclass->comment);
+  g_clear_pointer (&umlclass->name, g_free);
+  g_clear_pointer (&umlclass->stereotype, g_free);
+  g_clear_pointer (&umlclass->comment, g_free);
 
   list = umlclass->attributes;
   while (list != NULL) {
     attr = (UMLAttribute *)list->data;
-    g_free(attr->left_connection);
-    g_free(attr->right_connection);
+    g_clear_pointer (&attr->left_connection, g_free);
+    g_clear_pointer (&attr->right_connection, g_free);
     uml_attribute_unref (attr);
     list = g_list_next (list);
   }
@@ -1966,8 +1966,8 @@ umlclass_destroy(UMLClass *umlclass)
   list = umlclass->operations;
   while (list != NULL) {
     op = (UMLOperation *)list->data;
-    g_free (op->left_connection);
-    g_free (op->right_connection);
+    g_clear_pointer (&op->left_connection, g_free);
+    g_clear_pointer (&op->right_connection, g_free);
     uml_operation_unref (op);
     list = g_list_next (list);
   }
@@ -1976,9 +1976,7 @@ umlclass_destroy(UMLClass *umlclass)
   g_list_free_full (umlclass->formal_params, (GDestroyNotify) uml_formal_parameter_unref);
   umlclass->formal_params = NULL;
 
-  if (umlclass->stereotype_string != NULL) {
-    g_free (umlclass->stereotype_string);
-  }
+  g_clear_pointer (&umlclass->stereotype_string, g_free);
 
   if (umlclass->properties_dialog != NULL) {
     umlclass_dialog_free (umlclass->properties_dialog);
diff --git a/objects/UML/class_attributes_dialog.c b/objects/UML/class_attributes_dialog.c
index 184971ff..1bd8bfa7 100644
--- a/objects/UML/class_attributes_dialog.c
+++ b/objects/UML/class_attributes_dialog.c
@@ -109,7 +109,7 @@ attributes_set_values (UMLClassDialog *prop_dialog, UMLAttribute *attr)
   gtk_text_buffer_set_text (prop_dialog->attr_comment_buffer,
                             comment,
                             -1);
-  g_free (comment);
+  g_clear_pointer (&comment, g_free);
 
   dia_option_menu_set_active (DIA_OPTION_MENU (prop_dialog->attr_visible),
                               attr->visibility);
diff --git a/objects/UML/class_dialog.c b/objects/UML/class_dialog.c
index d1d3f98b..df8a47a7 100644
--- a/objects/UML/class_dialog.c
+++ b/objects/UML/class_dialog.c
@@ -51,7 +51,7 @@ umlclass_dialog_free (UMLClassDialog *dialog)
 {
   g_list_free(dialog->deleted_connections);
   gtk_widget_destroy(dialog->dialog);
-  /* destroy-signal destroy_properties_dialog already does 'g_free(dialog);' and more */
+  /* destroy-signal destroy_properties_dialog already does 'g_clear_pointer (&dialog, g_free);' and more */
 }
 
 typedef struct _Disconnect {
@@ -193,10 +193,9 @@ _class_set_comment (GtkTextView *view, gchar *text)
 static void
 class_read_from_dialog(UMLClass *umlclass, UMLClassDialog *prop_dialog)
 {
-  const gchar *s;
+  const char *s;
 
-  if (umlclass->name != NULL)
-    g_free(umlclass->name);
+  g_clear_pointer (&umlclass->name, g_free);
 
   s = gtk_entry_get_text (prop_dialog->classname);
   if (s && s[0])
@@ -204,8 +203,7 @@ class_read_from_dialog(UMLClass *umlclass, UMLClassDialog *prop_dialog)
   else
     umlclass->name = NULL;
 
-  if (umlclass->stereotype != NULL)
-    g_free(umlclass->stereotype);
+  g_clear_pointer (&umlclass->stereotype, g_free);
 
   s = gtk_entry_get_text(prop_dialog->stereotype);
   if (s && s[0])
@@ -213,8 +211,7 @@ class_read_from_dialog(UMLClass *umlclass, UMLClassDialog *prop_dialog)
   else
     umlclass->stereotype = NULL;
 
-  if (umlclass->comment != NULL)
-    g_free (umlclass->comment);
+  g_clear_pointer (&umlclass->comment, g_free);
 
   s = _class_get_comment(prop_dialog->comment);
   if (s && s[0])
@@ -573,8 +570,7 @@ destroy_properties_dialog (GtkWidget* widget,
   /* dialog gone, mark as such */
   UMLClass *umlclass = (UMLClass *) user_data;
 
-  g_free (umlclass->properties_dialog);
-  umlclass->properties_dialog = NULL;
+  g_clear_pointer (&umlclass->properties_dialog, g_free);
 }
 
 
@@ -747,9 +743,9 @@ umlclass_free_state (UMLClassState *state)
   g_clear_object (&state->abstract_classname_font);
   g_clear_object (&state->comment_font);
 
-  g_free (state->name);
-  g_free (state->stereotype);
-  g_free (state->comment);
+  g_clear_pointer (&state->name, g_free);
+  g_clear_pointer (&state->stereotype, g_free);
+  g_clear_pointer (&state->comment, g_free);
 
   g_list_free_full (state->attributes, (GDestroyNotify) uml_attribute_unref);
   g_list_free_full (state->operations, (GDestroyNotify) uml_operation_unref);
@@ -932,18 +928,12 @@ umlclass_set_state(UMLClass *umlclass, UMLClassState *state)
   umlclass->comment_font_height = state->comment_font_height;
 
   /* transfer ownership, but don't leak the previous font */
-  g_object_unref (umlclass->normal_font);
-  umlclass->normal_font = state->normal_font;
-  g_object_unref (umlclass->abstract_font);
-  umlclass->abstract_font = state->abstract_font;
-  g_object_unref (umlclass->polymorphic_font);
-  umlclass->polymorphic_font = state->polymorphic_font;
-  g_object_unref (umlclass->classname_font);
-  umlclass->classname_font = state->classname_font;
-  g_object_unref (umlclass->abstract_classname_font);
-  umlclass->abstract_classname_font = state->abstract_classname_font;
-  g_object_unref (umlclass->comment_font);
-  umlclass->comment_font = state->comment_font;
+  g_set_object (&umlclass->normal_font, state->normal_font);
+  g_set_object (&umlclass->abstract_font, state->abstract_font);
+  g_set_object (&umlclass->polymorphic_font, state->polymorphic_font);
+  g_set_object (&umlclass->classname_font, state->classname_font);
+  g_set_object (&umlclass->abstract_classname_font, state->abstract_classname_font);
+  g_set_object (&umlclass->comment_font, state->comment_font);
 
   umlclass->name = state->name;
   umlclass->stereotype = state->stereotype;
@@ -970,7 +960,7 @@ umlclass_set_state(UMLClass *umlclass, UMLClassState *state)
   umlclass->template = state->template;
   umlclass->formal_params = state->formal_params;
 
-  g_free(state);
+  g_clear_pointer (&state, g_free);
 
   umlclass_update_connectionpoints(umlclass);
 
@@ -1030,7 +1020,7 @@ umlclass_change_free(UMLClassChange *change)
   GList *list, *free_list;
 
   umlclass_free_state(change->saved_state);
-  g_free(change->saved_state);
+  g_clear_pointer (&change->saved_state, g_free);
 
   /* Doesn't this mean only one of add, delete can be done in each apply? */
   if (change->applied)
@@ -1044,7 +1034,7 @@ umlclass_change_free(UMLClassChange *change)
 
     g_assert(connection->connected == NULL); /* Paranoid */
     object_remove_connections_to(connection); /* Shouldn't be needed */
-    g_free(connection);
+    g_clear_pointer (&connection, g_free);
 
     list = g_list_next(list);
   }
diff --git a/objects/UML/class_operations_dialog.c b/objects/UML/class_operations_dialog.c
index 834a396e..65e63e31 100644
--- a/objects/UML/class_operations_dialog.c
+++ b/objects/UML/class_operations_dialog.c
@@ -179,7 +179,7 @@ parameters_set_values (UMLClassDialog *prop_dialog,
   gtk_text_buffer_set_text (prop_dialog->param_comment_buffer,
                             comment,
                             -1);
-  g_free (comment);
+  g_clear_pointer (&comment, g_free);
 
   dia_option_menu_set_active (DIA_OPTION_MENU (prop_dialog->param_kind),
                               param->kind);
@@ -418,7 +418,7 @@ operations_set_values (UMLClassDialog *prop_dialog, UMLOperation *op)
   gtk_text_buffer_set_text (prop_dialog->op_comment_buffer,
                             comment,
                             -1);
-  g_free (comment);
+  g_clear_pointer (&comment, g_free);
 
   dia_option_menu_set_active (DIA_OPTION_MENU (prop_dialog->op_visible),
                               op->visibility);
@@ -439,7 +439,7 @@ operations_set_values (UMLClassDialog *prop_dialog, UMLOperation *op)
     gtk_list_store_append (prop_dialog->parameters_store, &iter);
     update_parameter (prop_dialog, param, &iter);
 
-    g_free (str);
+    g_clear_pointer (&str, g_free);
 
     list = g_list_next (list);
   }
diff --git a/objects/UML/component.c b/objects/UML/component.c
index 9d1c08ba..c1728f44 100644
--- a/objects/UML/component.c
+++ b/objects/UML/component.c
@@ -166,8 +166,7 @@ component_set_props(Component *component, GPtrArray *props)
 {
   object_set_props_from_offsets(&component->element.object,
                                 component_offsets, props);
-  g_free(component->st_stereotype);
-  component->st_stereotype = NULL;
+  g_clear_pointer (&component->st_stereotype, g_free);
   component_update_data(component);
 }
 
@@ -439,8 +438,8 @@ static void
 component_destroy(Component *cmp)
 {
   text_destroy(cmp->text);
-  g_free(cmp->stereotype);
-  g_free(cmp->st_stereotype);
+  g_clear_pointer (&cmp->stereotype, g_free);
+  g_clear_pointer (&cmp->st_stereotype, g_free);
   element_destroy(&cmp->element);
 }
 
diff --git a/objects/UML/constraint.c b/objects/UML/constraint.c
index 4a8838c2..fc512798 100644
--- a/objects/UML/constraint.c
+++ b/objects/UML/constraint.c
@@ -165,8 +165,7 @@ constraint_set_props(Constraint *constraint, GPtrArray *props)
 {
   object_set_props_from_offsets(&constraint->connection.object,
                                 constraint_offsets, props);
-  g_free(constraint->brtext);
-  constraint->brtext = NULL;
+  g_clear_pointer (&constraint->brtext, g_free);
   constraint_update_data(constraint);
 }
 
@@ -339,8 +338,8 @@ constraint_destroy (Constraint *constraint)
 {
   connection_destroy (&constraint->connection);
   g_clear_object (&constraint->font);
-  g_free (constraint->brtext);
-  g_free (constraint->text);
+  g_clear_pointer (&constraint->brtext, g_free);
+  g_clear_pointer (&constraint->text, g_free);
 }
 
 static void
@@ -353,7 +352,7 @@ constraint_update_data(Constraint *constraint)
 
   if ((constraint->text) && (constraint->text[0] == '{')) {
     /* we might have a string loaded from an older dia. Clean it up. */
-    g_free(constraint->brtext);
+    g_clear_pointer (&constraint->brtext, g_free);
     constraint->brtext = constraint->text;
     constraint->text = bracketted_to_string(constraint->text,"{","}");
   } else if (!constraint->brtext) {
diff --git a/objects/UML/dependency.c b/objects/UML/dependency.c
index 6534c505..7cecb79f 100644
--- a/objects/UML/dependency.c
+++ b/objects/UML/dependency.c
@@ -170,21 +170,23 @@ dependency_get_props(Dependency * dependency, GPtrArray *props)
                                 dependency_offsets,props);
 }
 
+
 static void
-dependency_set_props(Dependency *dependency, GPtrArray *props)
+dependency_set_props (Dependency *dependency, GPtrArray *props)
 {
-  object_set_props_from_offsets(&dependency->orth.object,
-                                dependency_offsets, props);
-  g_free(dependency->st_stereotype);
-  dependency->st_stereotype = NULL;
-  dependency_update_data(dependency);
+  object_set_props_from_offsets (&dependency->orth.object,
+                                 dependency_offsets, props);
+  g_clear_pointer (&dependency->st_stereotype, g_free);
+  dependency_update_data (dependency);
 }
 
-static real
-dependency_distance_from(Dependency *dep, Point *point)
+
+static double
+dependency_distance_from (Dependency *dep, Point *point)
 {
   OrthConn *orth = &dep->orth;
-  return orthconn_distance_from(orth, point, dep->line_width);
+
+  return orthconn_distance_from (orth, point, dep->line_width);
 }
 
 static void
@@ -444,16 +446,18 @@ dependency_create(Point *startpoint,
   return (DiaObject *)dep;
 }
 
+
 static void
 dependency_destroy (Dependency *dep)
 {
-  g_free (dep->name);
-  g_free (dep->stereotype);
-  g_free (dep->st_stereotype);
+  g_clear_pointer (&dep->name, g_free);
+  g_clear_pointer (&dep->stereotype, g_free);
+  g_clear_pointer (&dep->st_stereotype, g_free);
   g_clear_object (&dep->font);
   orthconn_destroy (&dep->orth);
 }
 
+
 static DiaObject *
 dependency_load(ObjectNode obj_node, int version,DiaContext *ctx)
 {
diff --git a/objects/UML/generalization.c b/objects/UML/generalization.c
index 31193ec0..faed53df 100644
--- a/objects/UML/generalization.c
+++ b/objects/UML/generalization.c
@@ -164,23 +164,26 @@ generalization_get_props(Generalization * generalization, GPtrArray *props)
                                 generalization_offsets,props);
 }
 
+
 static void
-generalization_set_props(Generalization *generalization, GPtrArray *props)
+generalization_set_props (Generalization *generalization, GPtrArray *props)
 {
-  object_set_props_from_offsets(&generalization->orth.object,
-                                generalization_offsets, props);
-  g_free(generalization->st_stereotype);
-  generalization->st_stereotype = NULL;
-  generalization_update_data(generalization);
+  object_set_props_from_offsets (&generalization->orth.object,
+                                 generalization_offsets, props);
+  g_clear_pointer (&generalization->st_stereotype, g_free);
+  generalization_update_data (generalization);
 }
 
-static real
-generalization_distance_from(Generalization *genlz, Point *point)
+
+static double
+generalization_distance_from (Generalization *genlz, Point *point)
 {
   OrthConn *orth = &genlz->orth;
-  return orthconn_distance_from(orth, point, genlz->line_width);
+
+  return orthconn_distance_from (orth, point, genlz->line_width);
 }
 
+
 static void
 generalization_select(Generalization *genlz, Point *clicked_point,
                  DiaRenderer *interactive_renderer)
@@ -442,16 +445,18 @@ generalization_create(Point *startpoint,
   return (DiaObject *)genlz;
 }
 
+
 static void
 generalization_destroy (Generalization *genlz)
 {
-  g_free (genlz->name);
-  g_free (genlz->stereotype);
-  g_free (genlz->st_stereotype);
+  g_clear_pointer (&genlz->name, g_free);
+  g_clear_pointer (&genlz->stereotype, g_free);
+  g_clear_pointer (&genlz->st_stereotype, g_free);
   g_clear_object (&genlz->font);
   orthconn_destroy (&genlz->orth);
 }
 
+
 static DiaObject *
 generalization_load(ObjectNode obj_node, int version,DiaContext *ctx)
 {
diff --git a/objects/UML/implements.c b/objects/UML/implements.c
index 0c85f070..f2c8ad81 100644
--- a/objects/UML/implements.c
+++ b/objects/UML/implements.c
@@ -356,7 +356,7 @@ implements_destroy (Implements *implements)
 {
   connection_destroy (&implements->connection);
   g_clear_object (&implements->font);
-  g_free (implements->text);
+  g_clear_pointer (&implements->text, g_free);
 }
 
 static void
diff --git a/objects/UML/large_package.c b/objects/UML/large_package.c
index e1c3af3d..6bc2115a 100644
--- a/objects/UML/large_package.c
+++ b/objects/UML/large_package.c
@@ -174,16 +174,18 @@ largepackage_get_props(LargePackage * largepackage, GPtrArray *props)
                                 largepackage_offsets, props);
 }
 
+
 static void
-largepackage_set_props(LargePackage *largepackage, GPtrArray *props)
+largepackage_set_props (LargePackage *largepackage, GPtrArray *props)
 {
-  object_set_props_from_offsets(&largepackage->element.object,
-                                largepackage_offsets, props);
-  g_free(largepackage->st_stereotype);
-  largepackage->st_stereotype = NULL;
-  largepackage_update_data(largepackage);
+  object_set_props_from_offsets (&largepackage->element.object,
+                                 largepackage_offsets,
+                                 props);
+  g_clear_pointer (&largepackage->st_stereotype, g_free);
+  largepackage_update_data (largepackage);
 }
 
+
 static real
 largepackage_distance_from(LargePackage *pkg, Point *point)
 {
@@ -400,17 +402,19 @@ largepackage_create(Point *startpoint,
   return &pkg->element.object;
 }
 
+
 static void
 largepackage_destroy (LargePackage *pkg)
 {
   g_clear_object (&pkg->font);
-  g_free (pkg->stereotype);
-  g_free (pkg->st_stereotype);
-  g_free (pkg->name);
+  g_clear_pointer (&pkg->stereotype, g_free);
+  g_clear_pointer (&pkg->st_stereotype, g_free);
+  g_clear_pointer (&pkg->name, g_free);
 
   element_destroy (&pkg->element);
 }
 
+
 static DiaObject *
 largepackage_load(ObjectNode obj_node, int version,DiaContext *ctx)
 {
diff --git a/objects/UML/lifeline.c b/objects/UML/lifeline.c
index 9f73e0d6..50870b58 100644
--- a/objects/UML/lifeline.c
+++ b/objects/UML/lifeline.c
@@ -456,17 +456,19 @@ lifeline_change_revert(LifelineChange *change, DiaObject *obj)
   }
 }
 
+
 static void
-lifeline_change_free(LifelineChange *change)
+lifeline_change_free (LifelineChange *change)
 {
-  if( change->type == LIFELINE_CHANGE_ADD ||  change->type == LIFELINE_CHANGE_DEL ) {
+  if (change->type == LIFELINE_CHANGE_ADD ||
+      change->type == LIFELINE_CHANGE_DEL) {
     if (change->east->free)
-      change->east->free(change->east);
-    g_free(change->east);
+      change->east->free (change->east);
+    g_clear_pointer (&change->east, g_free);
 
     if (change->west->free)
-      change->west->free(change->west);
-    g_free(change->west);
+      change->west->free (change->west);
+    g_clear_pointer (&change->west, g_free);
   }
 }
 
diff --git a/objects/UML/message.c b/objects/UML/message.c
index f21ae9ea..5f0672e6 100644
--- a/objects/UML/message.c
+++ b/objects/UML/message.c
@@ -358,8 +358,9 @@ message_draw (Message *message, DiaRenderer *renderer)
                               &message->text_color);
   }
 
-  if (message->type == MESSAGE_CREATE || message->type == MESSAGE_DESTROY) {
-    g_free(mname);
+  if (message->type == MESSAGE_CREATE ||
+      message->type == MESSAGE_DESTROY) {
+    g_clear_pointer (&mname, g_free);
   }
 }
 
@@ -420,14 +421,16 @@ message_create(Point *startpoint,
   return &message->connection.object;
 }
 
+
 static void
-message_destroy(Message *message)
+message_destroy (Message *message)
 {
-  connection_destroy(&message->connection);
+  connection_destroy (&message->connection);
 
-  g_free(message->text);
+  g_clear_pointer (&message->text, g_free);
 }
 
+
 static void
 message_update_data(Message *message)
 {
diff --git a/objects/UML/object.c b/objects/UML/object.c
index 01efd9a4..9389f61a 100644
--- a/objects/UML/object.c
+++ b/objects/UML/object.c
@@ -197,19 +197,22 @@ static PropOffset objet_offsets[] = {
   { NULL, 0, 0 },
 };
 
+
 static void
-objet_get_props(Objet * objet, GPtrArray *props)
+objet_get_props (Objet * objet, GPtrArray *props)
 {
-  text_get_attributes(objet->text,&objet->text_attrs);
+  text_get_attributes (objet->text, &objet->text_attrs);
   /* the aligement is _not_ part of the deal */
   objet->text_attrs.alignment = ALIGN_CENTER;
-  if (objet->attrib) g_free(objet->attrib);
-  objet->attrib = text_get_string_copy(objet->attributes);
+  g_clear_pointer (&objet->attrib, g_free);
+  objet->attrib = text_get_string_copy (objet->attributes);
 
-  object_get_props_from_offsets(&objet->element.object,
-                                objet_offsets,props);
+  object_get_props_from_offsets (&objet->element.object,
+                                 objet_offsets,
+                                 props);
 }
 
+
 static void
 objet_set_props(Objet *objet, GPtrArray *props)
 {
@@ -223,8 +226,7 @@ objet_set_props(Objet *objet, GPtrArray *props)
   objet->text_attrs.alignment = ALIGN_LEFT;
   apply_textattr_properties(props,objet->attributes,"attrib",&objet->text_attrs);
   objet->text_attrs.alignment = ALIGN_CENTER;
-  g_free(objet->st_stereotype);
-  objet->st_stereotype = NULL;
+  g_clear_pointer (&objet->st_stereotype, g_free);
   objet_update_data(objet);
 }
 
@@ -516,20 +518,22 @@ objet_create(Point *startpoint,
   return &ob->element.object;
 }
 
+
 static void
-objet_destroy(Objet *ob)
+objet_destroy (Objet *ob)
 {
-  text_destroy(ob->text);
-  text_destroy(ob->attributes);
+  text_destroy (ob->text);
+  text_destroy (ob->attributes);
 
-  g_free(ob->stereotype);
-  g_free(ob->st_stereotype);
-  g_free(ob->exstate);
-  g_free(ob->attrib);
+  g_clear_pointer (&ob->stereotype, g_free);
+  g_clear_pointer (&ob->st_stereotype, g_free);
+  g_clear_pointer (&ob->exstate, g_free);
+  g_clear_pointer (&ob->attrib, g_free);
 
-  element_destroy(&ob->element);
+  element_destroy (&ob->element);
 }
 
+
 static DiaObject *
 objet_load(ObjectNode obj_node, int version,DiaContext *ctx)
 {
diff --git a/objects/UML/realizes.c b/objects/UML/realizes.c
index 3703605e..5a5da697 100644
--- a/objects/UML/realizes.c
+++ b/objects/UML/realizes.c
@@ -164,24 +164,27 @@ realizes_get_props(Realizes * realizes, GPtrArray *props)
                                 realizes_offsets,props);
 }
 
+
 static void
-realizes_set_props(Realizes *realizes, GPtrArray *props)
+realizes_set_props (Realizes *realizes, GPtrArray *props)
 {
-  object_set_props_from_offsets(&realizes->orth.object,
-                                realizes_offsets, props);
-  g_free(realizes->st_stereotype);
-  realizes->st_stereotype = NULL;
+  object_set_props_from_offsets (&realizes->orth.object,
+                                 realizes_offsets,
+                                 props);
+  g_clear_pointer (&realizes->st_stereotype, g_free);
   realizes_update_data(realizes);
 }
 
 
-static real
-realizes_distance_from(Realizes *realize, Point *point)
+static double
+realizes_distance_from (Realizes *realize, Point *point)
 {
   OrthConn *orth = &realize->orth;
-  return orthconn_distance_from(orth, point, realize->line_width);
+
+  return orthconn_distance_from (orth, point, realize->line_width);
 }
 
+
 static void
 realizes_select(Realizes *realize, Point *clicked_point,
                  DiaRenderer *interactive_renderer)
@@ -440,16 +443,18 @@ realizes_create(Point *startpoint,
   return &realize->orth.object;
 }
 
+
 static void
 realizes_destroy (Realizes *realize)
 {
-  g_free (realize->name);
-  g_free (realize->stereotype);
-  g_free (realize->st_stereotype);
+  g_clear_pointer (&realize->name, g_free);
+  g_clear_pointer (&realize->stereotype, g_free);
+  g_clear_pointer (&realize->st_stereotype, g_free);
   g_clear_object (&realize->font);
   orthconn_destroy (&realize->orth);
 }
 
+
 static DiaObject *
 realizes_load(ObjectNode obj_node, int version,DiaContext *ctx)
 {
diff --git a/objects/UML/small_package.c b/objects/UML/small_package.c
index b5b3ef49..9da0d8fb 100644
--- a/objects/UML/small_package.c
+++ b/objects/UML/small_package.c
@@ -161,19 +161,21 @@ smallpackage_get_props(SmallPackage * smallpackage,
                                 smallpackage_offsets,props);
 }
 
+
 static void
-smallpackage_set_props(SmallPackage *smallpackage,
-                       GPtrArray *props)
+smallpackage_set_props (SmallPackage *smallpackage,
+                        GPtrArray    *props)
 {
-  object_set_props_from_offsets(&smallpackage->element.object,
-                                smallpackage_offsets, props);
-  g_free(smallpackage->st_stereotype);
-  smallpackage->st_stereotype = NULL;
+  object_set_props_from_offsets (&smallpackage->element.object,
+                                 smallpackage_offsets,
+                                 props);
+  g_clear_pointer (&smallpackage->st_stereotype, g_free);
   smallpackage_update_data(smallpackage);
 }
 
-static real
-smallpackage_distance_from(SmallPackage *pkg, Point *point)
+
+static double
+smallpackage_distance_from (SmallPackage *pkg, Point *point)
 {
   /* need to calculate the distance from both rects to make the autogap
    * use the right boundaries
@@ -390,17 +392,19 @@ smallpackage_create(Point *startpoint,
   return &pkg->element.object;
 }
 
+
 static void
-smallpackage_destroy(SmallPackage *pkg)
+smallpackage_destroy (SmallPackage *pkg)
 {
-  text_destroy(pkg->text);
+  text_destroy (pkg->text);
 
-  g_free(pkg->stereotype);
-  g_free(pkg->st_stereotype);
+  g_clear_pointer (&pkg->stereotype, g_free);
+  g_clear_pointer (&pkg->st_stereotype, g_free);
 
-  element_destroy(&pkg->element);
+  element_destroy (&pkg->element);
 }
 
+
 static DiaObject *
 smallpackage_load(ObjectNode obj_node, int version,DiaContext *ctx)
 {
diff --git a/objects/UML/state.c b/objects/UML/state.c
index c886003f..963bdd53 100644
--- a/objects/UML/state.c
+++ b/objects/UML/state.c
@@ -62,11 +62,11 @@ struct _State {
   Color line_color;
   Color fill_color;
 
-  real line_width;
+  double line_width;
 
-  gchar* entry_action;
-  gchar* do_action;
-  gchar* exit_action;
+  char *entry_action;
+  char *do_action;
+  char *exit_action;
 };
 
 
@@ -96,7 +96,7 @@ static PropDescription *state_describe_props(State *state);
 static void state_get_props(State *state, GPtrArray *props);
 static void state_set_props(State *state, GPtrArray *props);
 static void state_update_data(State *state);
-static gchar* state_get_action_text(State* state, StateAction action);
+static char* state_get_action_text (State* state, StateAction action);
 static void state_calc_action_text_pos(State* state, StateAction action, Point* pos);
 
 static ObjectTypeOps state_type_ops =
@@ -244,11 +244,15 @@ state_move(State *state, Point *to)
   return NULL;
 }
 
+
 static void
-state_draw_action_string (State *state, DiaRenderer *renderer, StateAction action)
+state_draw_action_string (State       *state,
+                          DiaRenderer *renderer,
+                          StateAction  action)
 {
   Point pos;
-  gchar* action_text = state_get_action_text (state, action);
+  char *action_text = state_get_action_text (state, action);
+
   state_calc_action_text_pos (state, action, &pos);
   dia_renderer_set_font (renderer, state->text->font, state->text->height);
   dia_renderer_draw_string (renderer,
@@ -256,9 +260,10 @@ state_draw_action_string (State *state, DiaRenderer *renderer, StateAction actio
                             &pos,
                             ALIGN_LEFT,
                             &state->text->color);
-  g_free (action_text);
+  g_clear_pointer (&action_text, g_free);
 }
 
+
 static void
 state_draw (State *state, DiaRenderer *renderer)
 {
@@ -343,22 +348,25 @@ state_draw (State *state, DiaRenderer *renderer)
 
 
 static void
-state_update_width_and_height_with_action_text(State* state,
-                                               StateAction action,
-                                               real* width,
-                                               real* height)
+state_update_width_and_height_with_action_text (State       *state,
+                                                StateAction  action,
+                                                double      *width,
+                                                double      *height)
 {
-  gchar* action_text = state_get_action_text(state, action);
-  *width = MAX(*width, dia_font_string_width(action_text, state->text->font,
-                                             state->text->height) + 2*STATE_MARGIN_X);
-  g_free(action_text);
+  char *action_text = state_get_action_text (state, action);
+  *width = MAX (*width,
+                dia_font_string_width (action_text,
+                                       state->text->font,
+                                       state->text->height) + 2 * STATE_MARGIN_X);
+  g_clear_pointer (&action_text, g_free);
   *height += state->text->height;
 }
 
+
 static void
-state_update_data(State *state)
+state_update_data (State *state)
 {
-  real w, h;
+  double w, h;
 
   Element *elem = &state->element;
   ElementBBExtras *extra = &elem->extra_spacing;
@@ -468,9 +476,9 @@ state_create(Point *startpoint,
 static void
 state_destroy (State *state)
 {
-  g_free (state->entry_action);
-  g_free (state->do_action);
-  g_free (state->exit_action);
+  g_clear_pointer (&state->entry_action, g_free);
+  g_clear_pointer (&state->do_action, g_free);
+  g_clear_pointer (&state->exit_action, g_free);
 
   text_destroy (state->text);
 
@@ -533,7 +541,7 @@ state_calc_action_text_pos (State* state, StateAction action, Point* pos)
 }
 
 
-static gchar*
+static char *
 state_get_action_text (State* state, StateAction action)
 {
   switch (action) {
diff --git a/objects/UML/stereotype.c b/objects/UML/stereotype.c
index c15f1ec5..99db005b 100644
--- a/objects/UML/stereotype.c
+++ b/objects/UML/stereotype.c
@@ -23,18 +23,20 @@
 #include <string.h>
 #include "stereotype.h"
 
-gchar *
-string_to_bracketted (gchar *str, 
-                     const char *start_bracket, 
-                     const char *end_bracket)
+
+char *
+string_to_bracketted (char       *str,
+                      const char *start_bracket,
+                      const char *end_bracket)
 {
   return g_strconcat (start_bracket, (str ? str : ""), end_bracket, NULL);
 }
 
-gchar *
-bracketted_to_string (gchar *bracketted,
-                     const char *start_bracket,
-                     const char *end_bracket)
+
+char *
+bracketted_to_string (char       *bracketted,
+                      const char *start_bracket,
+                      const char *end_bracket)
 {
   const char *utfstart, *utfend, *utfstr;
   int start_len, end_len, str_len;
@@ -60,30 +62,38 @@ bracketted_to_string (gchar *bracketted,
   return g_strndup (utfstr, str_len);
 }
 
-gchar *
-string_to_stereotype (gchar *str)
+
+char *
+string_to_stereotype (char *str)
 {
-  if ((str) && str[0] != '\0')  
-    return string_to_bracketted(str, UML_STEREOTYPE_START, UML_STEREOTYPE_END);
-  return g_strdup(str);
+  if ((str) && str[0] != '\0') {
+    return string_to_bracketted (str,
+                                 UML_STEREOTYPE_START,
+                                 UML_STEREOTYPE_END);
+  }
+  return g_strdup (str);
 }
 
-gchar *
-remove_stereotype_from_string (gchar *stereotype)
+
+char *
+remove_stereotype_from_string (char *stereotype)
 {
-  if (stereotype) { 
-    char *tmp = bracketted_to_string (stereotype, 
-                                        UML_STEREOTYPE_START, UML_STEREOTYPE_END);
-    g_free(stereotype);
+  if (stereotype) {
+    char *tmp = bracketted_to_string (stereotype,
+                                      UML_STEREOTYPE_START,
+                                      UML_STEREOTYPE_END);
+    g_free (stereotype);
     return tmp;
   } else {
     return NULL;
   }
 }
 
-gchar *
-stereotype_to_string (gchar *stereotype)
+
+char *
+stereotype_to_string (char *stereotype)
 {
-  return bracketted_to_string(stereotype, 
-                              UML_STEREOTYPE_START, UML_STEREOTYPE_END);
+  return bracketted_to_string (stereotype,
+                               UML_STEREOTYPE_START,
+                               UML_STEREOTYPE_END);
 }
diff --git a/objects/UML/transition.c b/objects/UML/transition.c
index 214b579a..54040b98 100644
--- a/objects/UML/transition.c
+++ b/objects/UML/transition.c
@@ -41,11 +41,11 @@ struct _Transition {
 
   Handle trigger_text_handle;
   Point trigger_text_pos;
-  gchar *trigger_text;
-  gchar *action_text;
+  char *trigger_text;
+  char *action_text;
   Handle guard_text_handle;
   Point guard_text_pos;
-  gchar *guard_text;
+  char *guard_text;
   gboolean direction_inverted;
 };
 
@@ -291,11 +291,11 @@ transition_describe_props (Transition *transition)
 
 
 static void
-transition_destroy(Transition* transition)
+transition_destroy (Transition* transition)
 {
-  g_free (transition->trigger_text);
-  g_free (transition->action_text);
-  g_free (transition->guard_text);
+  g_clear_pointer (&transition->trigger_text, g_free);
+  g_clear_pointer (&transition->action_text, g_free);
+  g_clear_pointer (&transition->guard_text, g_free);
   orthconn_destroy (&transition->orth);
 }
 
@@ -317,10 +317,10 @@ transition_get_object_menu (Transition *transition, Point *clickedpoint)
 }
 
 
-static gchar *
+static char *
 create_event_action_text (Transition* transition)
 {
-  gchar *temp_text;
+  char *temp_text;
 
   if (transition->action_text && strlen (transition->action_text) != 0) {
     temp_text = g_strdup_printf ("%s/%s", transition->trigger_text,
@@ -334,12 +334,10 @@ create_event_action_text (Transition* transition)
 }
 
 
-static gchar *
+static char *
 create_guard_text (Transition* transition)
 {
-  gchar *temp_text;
-  temp_text = g_strdup_printf ("[%s]", transition->guard_text);
-  return temp_text;
+  return g_strdup_printf ("[%s]", transition->guard_text);
 }
 
 
@@ -394,29 +392,29 @@ transition_draw (Transition *transition, DiaRenderer *renderer)
 
   /* Draw the guard text */
   if (transition->guard_text && strlen (transition->guard_text) != 0) {
-    gchar *text = create_guard_text (transition);
+    char *text = create_guard_text (transition);
     dia_renderer_draw_string (renderer,
                               text,
                               &transition->guard_text_pos,
                               ALIGN_CENTER,
                               &transition->text_color);
-    g_free (text);
+    g_clear_pointer (&text, g_free);
   }
 
   /* Draw the trigger text */
   if (transition->trigger_text && strlen (transition->trigger_text) != 0) {
-    gchar *text = create_event_action_text (transition);
+    char *text = create_event_action_text (transition);
     dia_renderer_draw_string (renderer,
                               text,
                               &transition->trigger_text_pos,
                               ALIGN_CENTER,
                               &transition->text_color);
-    g_free (text);
+    g_clear_pointer (&text, g_free);
   }
 }
 
 
-static real
+static double
 transition_distance (Transition *transition, Point *point)
 {
   return orthconn_distance_from (&transition->orth, point, TRANSITION_WIDTH);
@@ -561,10 +559,10 @@ transition_del_segment_cb (DiaObject *obj,
 static void
 expand_bbox_for_text (DiaRectangle *bbox,
                       Point        *text_pos,
-                      gchar        *text)
+                      char         *text)
 {
   DiaRectangle text_box;
-  real text_width;
+  double text_width;
 
   text_width = dia_font_string_width (text, transition_font,
                                       TRANSITION_FONTHEIGHT);
@@ -580,7 +578,7 @@ expand_bbox_for_text (DiaRectangle *bbox,
 static void
 uml_transition_update_data (Transition *transition)
 {
-  gchar *temp_text;
+  char *temp_text;
   Point *points;
 
   /* Setup helpful pointers as shortcuts */
@@ -609,10 +607,10 @@ uml_transition_update_data (Transition *transition)
   temp_text = create_event_action_text (transition);
   expand_bbox_for_text (&obj->bounding_box, &transition->trigger_text_pos,
                         temp_text);
-  g_free (temp_text);
+  g_clear_pointer (&temp_text, g_free);
   /* Update the bounding box to match the new guard text size and position */
   temp_text = g_strdup_printf ("[%s]", transition->guard_text ? transition->guard_text : "");
   expand_bbox_for_text (&obj->bounding_box, &transition->guard_text_pos,
                         temp_text);
-  g_free (temp_text);
+  g_clear_pointer (&temp_text, g_free);
 }
diff --git a/objects/UML/umlattribute.c b/objects/UML/umlattribute.c
index af2da73e..753d638b 100644
--- a/objects/UML/umlattribute.c
+++ b/objects/UML/umlattribute.c
@@ -154,13 +154,13 @@ uml_attribute_ref (UMLAttribute *self)
 static void
 attribute_destroy (UMLAttribute *attr)
 {
-  g_free (attr->name);
-  g_free (attr->type);
-  g_free (attr->value);
-  g_free (attr->comment);
+  g_clear_pointer (&attr->name, g_free);
+  g_clear_pointer (&attr->type, g_free);
+  g_clear_pointer (&attr->value, g_free);
+  g_clear_pointer (&attr->comment, g_free);
 #if 0 /* free'd elsewhere */
-  g_free(attr->left_connection);
-  g_free(attr->right_connection);
+  g_clear_pointer (&attr->left_connection, g_free);
+  g_clear_pointer (&attr->right_connection, g_free);
 #endif
 }
 
diff --git a/objects/UML/umlformalparameter.c b/objects/UML/umlformalparameter.c
index 837f8139..4b6fc823 100644
--- a/objects/UML/umlformalparameter.c
+++ b/objects/UML/umlformalparameter.c
@@ -91,8 +91,8 @@ uml_formal_parameter_ref (UMLFormalParameter *param)
 static void
 formal_parameter_destroy (UMLFormalParameter *param)
 {
-  g_free (param->name);
-  g_free (param->type);
+  g_clear_pointer (&param->name, g_free);
+  g_clear_pointer (&param->type, g_free);
 }
 
 
diff --git a/objects/UML/umloperation.c b/objects/UML/umloperation.c
index 39782435..deac13d5 100644
--- a/objects/UML/umloperation.c
+++ b/objects/UML/umloperation.c
@@ -132,37 +132,17 @@ uml_operation_copy_into (UMLOperation *srcop, UMLOperation *destop)
 
   destop->internal_id = srcop->internal_id;
 
-  if (destop->name != NULL) {
-    g_free (destop->name);
-  }
+  g_clear_pointer (&destop->name, g_free);
   destop->name = g_strdup (srcop->name);
 
-  if (destop->type != NULL) {
-    g_free (destop->type);
-  }
-  if (srcop->type != NULL) {
-    destop->type = g_strdup (srcop->type);
-  } else {
-    destop->type = NULL;
-  }
+  g_clear_pointer (&destop->type, g_free);
+  destop->type = g_strdup (srcop->type);
 
-  if (destop->stereotype != NULL) {
-    g_free (destop->stereotype);
-  }
-  if(srcop->stereotype != NULL) {
-    destop->stereotype = g_strdup (srcop->stereotype);
-  } else {
-    destop->stereotype = NULL;
-  }
+  g_clear_pointer (&destop->stereotype, g_free);
+  destop->stereotype = g_strdup (srcop->stereotype);
 
-  if (destop->comment != NULL) {
-    g_free (destop->comment);
-  }
-  if (srcop->comment != NULL) {
-    destop->comment = g_strdup (srcop->comment);
-  } else {
-    destop->comment = NULL;
-  }
+  g_clear_pointer (&destop->comment, g_free);
+  destop->comment = g_strdup (srcop->comment);
 
   destop->visibility = srcop->visibility;
   destop->class_scope = srcop->class_scope;
@@ -219,13 +199,10 @@ uml_operation_ref (UMLOperation *self)
 static void
 operation_free (UMLOperation *op)
 {
-  g_free (op->name);
-  if (op->type != NULL)
-    g_free (op->type);
-  if (op->stereotype != NULL)
-    g_free (op->stereotype);
-
-  g_free (op->comment);
+  g_clear_pointer (&op->name, g_free);
+  g_clear_pointer (&op->type, g_free);
+  g_clear_pointer (&op->stereotype, g_free);
+  g_clear_pointer (&op->comment, g_free);
 
   g_list_free_full (op->parameters, (GDestroyNotify) uml_parameter_unref);
 
@@ -235,8 +212,8 @@ operation_free (UMLOperation *op)
 
 #if 0 /* freed elsewhere */
   /* These are merely temporary reminders, don't need to unconnect */
-  g_free(op->left_connection);
-  g_free(op->right_connection);
+  g_clear_pointer (&op->left_connection, g_free);
+  g_clear_pointer (&op->right_connection, g_free);
 #endif
 }
 
diff --git a/objects/chronogram/chronoline.c b/objects/chronogram/chronoline.c
index a9e8e2f0..90cab152 100644
--- a/objects/chronogram/chronoline.c
+++ b/objects/chronogram/chronoline.c
@@ -670,8 +670,8 @@ chronoline_create(Point *startpoint,
 static void
 chronoline_destroy (Chronoline *chronoline)
 {
-  g_free (chronoline->name);
-  g_free (chronoline->events);
+  g_clear_pointer (&chronoline->name, g_free);
+  g_clear_pointer (&chronoline->events, g_free);
   g_clear_object (&chronoline->font);
   connpointline_destroy (chronoline->snap);
   destroy_clevent_list (chronoline->evtlist);
diff --git a/objects/chronogram/chronoline_event.c b/objects/chronogram/chronoline_event.c
index 9a8f5b80..f723e5d4 100644
--- a/objects/chronogram/chronoline_event.c
+++ b/objects/chronogram/chronoline_event.c
@@ -57,10 +57,10 @@ compare_cle (gconstpointer a, gconstpointer b)
 
 
 void
-destroy_cle(gpointer data, gpointer user_data)
+destroy_cle (gpointer data, gpointer user_data)
 {
-  CLEvent *cle = (CLEvent *)data;
-  g_free(cle);
+  CLEvent *cle = (CLEvent *) data;
+  g_clear_pointer (&cle, g_free);
 }
 
 
@@ -321,7 +321,7 @@ reparse_clevent(const gchar *events, CLEventList **lst,
   destroy_clevent_list(*lst);
   *lst = parse_clevent(ps,rise,fall);
   if (ps != events)
-    g_free(ps);
+    g_clear_pointer (&ps, g_free);
   *chksum = newsum;
 }
 
diff --git a/objects/custom/custom.c b/objects/custom/custom.c
index 5de009dd..cae9dd9a 100644
--- a/objects/custom/custom.c
+++ b/objects/custom/custom.c
@@ -39,14 +39,14 @@
 void custom_object_new (ShapeInfo *info,
                         DiaObjectType **otype);
 
-G_MODULE_EXPORT gboolean custom_object_load(gchar *filename, 
-                                            DiaObjectType **otype);
+G_MODULE_EXPORT gboolean custom_object_load (char           *filename,
+                                             DiaObjectType **otype);
 
 /* Cannot be static, because we may use this fn later when loading
    a new shape via the sheets dialog */
-   
+
 G_MODULE_EXPORT gboolean
-custom_object_load(gchar *filename, DiaObjectType **otype)
+custom_object_load (char *filename, DiaObjectType **otype)
 {
   ShapeInfo *info;
 
@@ -55,29 +55,30 @@ custom_object_load(gchar *filename, DiaObjectType **otype)
   info = shape_info_load(filename);
   /*g_assert(info);*/
   if (!info) {
-    *otype = NULL; 
+    *otype = NULL;
     return FALSE;
   }
   custom_object_new(info, otype);
   return TRUE;
 }
 
+
 static gboolean
-custom_object_preload(gchar *filename, DiaObjectType **otype)
+custom_object_preload (char *filename, DiaObjectType **otype)
 {
   ShapeInfo *info;
-  
+
   info = g_new0 (ShapeInfo, 1);
   info->filename = g_strdup (filename);
   /* Just enough to register the type, not enough to create the object */
   if (!shape_typeinfo_load(info)) {
-    /* there are currently 5 - out of ~700 shapes - which fail the size assumption 
+    /* there are currently 5 - out of ~700 shapes - which fail the size assumption
      * (reading only the first 512 bytes of the shape).
      * Instead of not loading them at all, they are loaded  completely as a fallback.
      * Another way would be to increase the size to read for every shape, seems worse.
      */
-     g_free (info->filename);
-     g_free (info);
+     g_clear_pointer (&info->filename, g_free);
+     g_clear_pointer (&info, g_free);
      if ((info = shape_info_load(filename)) == NULL)
        return FALSE;
   }
@@ -85,8 +86,10 @@ custom_object_preload(gchar *filename, DiaObjectType **otype)
   custom_object_new(info, otype);
   return TRUE;
 }
-static void 
-load_shapes_from_tree(const gchar *directory)
+
+
+static void
+load_shapes_from_tree (const char *directory)
 {
   GDir *dp;
   const char *dentry;
@@ -95,23 +98,23 @@ load_shapes_from_tree(const gchar *directory)
   if (dp == NULL) {
     return;
   }
-  while ( (dentry = g_dir_read_name(dp)) ) {
-    gchar *filename = g_strconcat(directory, G_DIR_SEPARATOR_S,
-                                 dentry, NULL);
-    const gchar *p;
+
+  while ((dentry = g_dir_read_name(dp))) {
+    char *filename = g_build_filename (directory, dentry, NULL);
+    const char *p;
 
     if (g_file_test(filename, G_FILE_TEST_IS_DIR)) {
       load_shapes_from_tree(filename);
-      g_free(filename);
+      g_clear_pointer (&filename, g_free);
       continue;
     }
     /* if it's not a directory, then it must be a .shape file */
     if (   !g_file_test(filename, G_FILE_TEST_IS_REGULAR)
         || (strlen(dentry) < 6)) {
-      g_free(filename);
+      g_clear_pointer (&filename, g_free);
       continue;
     }
-    
+
     p = dentry + strlen(dentry) - 6;
     if (0==strcmp(".shape",p)) {
       DiaObjectType *ot;
@@ -119,47 +122,52 @@ load_shapes_from_tree(const gchar *directory)
       if (!custom_object_preload(filename, &ot)) {
         g_warning("could not load shape file %s",filename);
       } else {
-        g_assert(ot); 
+        g_assert(ot);
         g_assert(ot->default_user_data);
         object_register_type(ot);
       }
     }
-    g_free(filename);
+    g_clear_pointer (&filename, g_free);
   }
   g_dir_close(dp);
 }
 
 DIA_PLUGIN_CHECK_INIT
 
+
 PluginInitResult
-dia_plugin_init(PluginInfo *info)
+dia_plugin_init (PluginInfo *info)
 {
   char *shape_path;
-  const char *home_dir;
+  char *home_dir;
 
-  if (!dia_plugin_info_init(info, _("Custom"), _("Custom XML shapes loader"),
-                           NULL, NULL))
+  if (!dia_plugin_info_init (info,
+                             _("Custom"),
+                             _("Custom XML shapes loader"),
+                             NULL,
+                             NULL)) {
     return DIA_PLUGIN_INIT_ERROR;
+  }
 
-  home_dir = g_get_home_dir();
-  if (home_dir) {
-    home_dir = dia_config_filename("shapes");
-    load_shapes_from_tree(home_dir);
-    g_free((char *)home_dir);
+  if (g_get_home_dir ()) {
+    home_dir = dia_config_filename ("shapes");
+    load_shapes_from_tree (home_dir);
+    g_clear_pointer (&home_dir, g_free);
   }
 
-  shape_path = getenv("DIA_SHAPE_PATH");
+  shape_path = getenv ("DIA_SHAPE_PATH");
   if (shape_path) {
-    char **dirs = g_strsplit(shape_path, G_SEARCHPATH_SEPARATOR_S, 0);
+    char **dirs = g_strsplit (shape_path, G_SEARCHPATH_SEPARATOR_S, 0);
     int i;
 
-    for (i = 0; dirs[i] != NULL; i++)
-      load_shapes_from_tree(dirs[i]);
-    g_strfreev(dirs);
+    for (i = 0; dirs[i] != NULL; i++) {
+      load_shapes_from_tree (dirs[i]);
+    }
+    g_strfreev (dirs);
   } else {
-    char *thedir = dia_get_data_directory("shapes");
-    load_shapes_from_tree(thedir);
-    g_free(thedir);
+    char *thedir = dia_get_data_directory ("shapes");
+    load_shapes_from_tree (thedir);
+    g_clear_pointer (&thedir, g_free);
   }
 
   return DIA_PLUGIN_INIT_OK;
diff --git a/objects/custom/custom_object.c b/objects/custom/custom_object.c
index 3e4b5142..d876fb9b 100644
--- a/objects/custom/custom_object.c
+++ b/objects/custom/custom_object.c
@@ -317,38 +317,36 @@ custom_setup_properties (ShapeInfo *info, xmlNodePtr node)
        continue;
       if (node->type != XML_ELEMENT_NODE)
        continue;
-      if (!xmlStrcmp(node->name, (const xmlChar *)"ext_attribute"))
-      {
-       gchar *pname, *ptype = 0;
-
-       str = xmlGetProp(node, (const xmlChar *)"name");
-       if (!str)
-         continue;
-       pname = g_strdup((gchar *) str);
-       xmlFree(str);
-
-       str = xmlGetProp(node, (const xmlChar *)"type");
-       if (!str)
-       {
-         g_free (pname);
-         continue;
-       }
-       ptype = g_strdup((gchar *) str);
-       xmlFree(str);
-
-       /* we got here, then fill an entry */
-       info->props[i].name = g_strdup_printf("custom:%s", pname);
-       info->props[i].type = ptype;
-       info->props[i].flags = PROP_FLAG_VISIBLE|PROP_FLAG_OPTIONAL;
-
-       str = xmlGetProp(node, (const xmlChar *)"description");
-       if (str)
-       {
-         g_free (pname);
-         pname = g_strdup((gchar *) str);
-         xmlFree(str);
-       }
-       info->props[i++].description = pname;
+      if (!xmlStrcmp(node->name, (const xmlChar *) "ext_attribute")) {
+      char *pname, *ptype = 0;
+
+      str = xmlGetProp(node, (const xmlChar *)"name");
+      if (!str) {
+        continue;
+      }
+      pname = g_strdup((char *) str);
+      xmlFree(str);
+
+      str = xmlGetProp(node, (const xmlChar *)"type");
+      if (!str) {
+        g_clear_pointer (&pname, g_free);
+        continue;
+      }
+      ptype = g_strdup((char *) str);
+      xmlFree(str);
+
+      /* we got here, then fill an entry */
+      info->props[i].name = g_strdup_printf ("custom:%s", pname);
+      info->props[i].type = ptype;
+      info->props[i].flags = PROP_FLAG_VISIBLE|PROP_FLAG_OPTIONAL;
+
+        str = xmlGetProp (node, (const xmlChar *) "description");
+        if (str) {
+          g_clear_pointer (&pname, g_free);
+          pname = g_strdup ((char *) str);
+          xmlFree (str);
+        }
+        info->props[i++].description = pname;
       }
     }
   }
@@ -1449,7 +1447,7 @@ custom_update_data(Custom *custom, AnchorShape horiz, AnchorShape vert)
             custom->text->height * custom->text->numlines) / 2 +
        dia_font_ascent(txs,custom->text->font, custom->text->height);
     text_set_position(custom->text, &p);
-    g_free(txs);
+    g_clear_pointer (&txs, g_free);
   }
 
   for (i = 0; i < info->nconnections; i++)
@@ -1762,7 +1760,7 @@ custom_destroy(Custom *custom)
 
   element_destroy(&custom->element);
 
-  g_free(custom->connections);
+  g_clear_pointer (&custom->connections, g_free);
 }
 
 static DiaObject *
diff --git a/objects/custom/custom_util.c b/objects/custom/custom_util.c
index e276affc..0815d632 100644
--- a/objects/custom/custom_util.c
+++ b/objects/custom/custom_util.c
@@ -23,18 +23,21 @@
 
 #include "custom_util.h"
 
-gchar *
-custom_get_relative_filename(const gchar *current, const gchar *relative)
+
+char *
+custom_get_relative_filename (const char *current, const gchar *relative)
 {
-  gchar *dirname, *tmp;
+  char *dirname, *tmp;
 
   g_return_val_if_fail(current != NULL, NULL);
   g_return_val_if_fail(relative != NULL, NULL);
 
-  if (g_path_is_absolute(relative))
-    return g_strdup(relative);
-  dirname = g_path_get_dirname(current);
-  tmp = g_build_filename(dirname, relative, NULL);
-  g_free(dirname);
+  if (g_path_is_absolute (relative)) {
+    return g_strdup (relative);
+  }
+
+  dirname = g_path_get_dirname (current);
+  tmp = g_build_filename (dirname, relative, NULL);
+  g_clear_pointer (&dirname, g_free);
   return tmp;
 }
diff --git a/objects/custom/shape_info.c b/objects/custom/shape_info.c
index da46eca1..a3359c95 100644
--- a/objects/custom/shape_info.c
+++ b/objects/custom/shape_info.c
@@ -479,32 +479,35 @@ parse_svg_node(ShapeInfo *info, xmlNodePtr node, xmlNsPtr svg_ns,
       if (!str) /* this doesn't look right but it appears to work w/o namespace --hb */
         str = xmlGetProp(node, (const xmlChar *)"href");
       if (str) {
-        gchar *imgfn = NULL;
-        const char* data = strchr((char *)str, ',');
+        char *imgfn = NULL;
+        const char* data = strchr ((char *) str, ',');
 
-       /* first check for inlined data */
-       if (data) {
-         GdkPixbuf *pixbuf = pixbuf_decode_base64 (data+1);
+        /* first check for inlined data */
+        if (data) {
+          GdkPixbuf *pixbuf = pixbuf_decode_base64 (data + 1);
 
-         if (pixbuf) {
-           image->image = dia_image_new_from_pixbuf (pixbuf);
-           g_object_unref (pixbuf);
-         }
-       } else {
-         imgfn = g_filename_from_uri((gchar *) str, NULL, NULL);
-          if (!imgfn)
-           /* despite it's name it ensures an absolute filename */
-            imgfn = custom_get_relative_filename(filename, (gchar *) str);
+          if (pixbuf) {
+            image->image = dia_image_new_from_pixbuf (pixbuf);
+            g_clear_object (&pixbuf);
+          }
+        } else {
+          imgfn = g_filename_from_uri ((char *) str, NULL, NULL);
+          if (!imgfn) {
+            /* despite it's name it ensures an absolute filename */
+            imgfn = custom_get_relative_filename (filename, (char *) str);
+          }
+
+          image->image = dia_image_load (imgfn);
+        }
 
-          image->image = dia_image_load(imgfn);
-       }
         if (!image->image) {
           g_debug ("%s: failed to load image file %s",
                    G_STRLOC,
                    imgfn ? imgfn : "(data:)");
         }
-        g_free(imgfn);
-        xmlFree(str);
+
+        g_clear_pointer (&imgfn, g_free);
+        xmlFree (str);
       }
       /* w/o the image we would crash later */
       if (!image->image)
@@ -762,18 +765,18 @@ load_shape_info (const gchar *filename, ShapeInfo *preload)
           g_warning ("Shape(preload) '%s' can't change name '%s'", info->name, tmp);
         /* the key name is already used as key in name_to_info */
       } else {
-        g_free(info->name);
+        g_clear_pointer (&info->name, g_free);
         info->name = g_strdup(tmp);
       }
       xmlFree(tmp);
     } else if (node->ns == shape_ns && !xmlStrcmp(node->name, (const xmlChar *)"icon")) {
-      tmp = (gchar *) xmlNodeGetContent(node);
+      tmp = (char *) xmlNodeGetContent(node);
       if (preload) {
         if (strstr (info->icon, tmp) == NULL) /* the left including the absolute path */
           g_warning ("Shape(preload) '%s' can't change icon '%s'", info->icon, tmp);
         /* the key name is already used as key in name_to_info */
       } else {
-        g_free(info->icon);
+        g_clear_pointer (&info->icon, g_free);
         info->icon = custom_get_relative_filename(filename, tmp);
       }
       xmlFree(tmp);
@@ -784,35 +787,37 @@ load_shape_info (const gchar *filename, ShapeInfo *preload)
       for (pt_node = node->xmlChildrenNode;
            pt_node != NULL;
            pt_node = pt_node->next) {
-        if (xmlIsBlankNode(pt_node)) continue;
+        if (xmlIsBlankNode(pt_node)) {
+          continue;
+        }
 
-       if (pt_node->ns == shape_ns && !xmlStrcmp(pt_node->name, (const xmlChar *)"point")) {
-         Point pt = { 0.0, 0.0 };
-         xmlChar *str;
+        if (pt_node->ns == shape_ns && !xmlStrcmp(pt_node->name, (const xmlChar *)"point")) {
+          Point pt = { 0.0, 0.0 };
+          xmlChar *str;
 
-         str = xmlGetProp(pt_node, (const xmlChar *)"x");
-         if (str) {
-           pt.x = g_ascii_strtod((gchar *) str, NULL);
-           xmlFree(str);
-         }
-         str = xmlGetProp(pt_node, (const xmlChar *)"y");
-         if (str) {
-           pt.y = g_ascii_strtod((gchar *) str, NULL);
-           xmlFree(str);
-         }
-         g_array_append_val(arr, pt);
-         str = xmlGetProp(pt_node, (const xmlChar *)"main");
-         if (str && str[0] != '\0') {
-           if (info->main_cp != -1) {
-             message_warning("More than one main connection point in %s.  Only the first one will be 
used.\n",
-                             info->name);
-           } else {
-             info->main_cp = i;
-           }
-           xmlFree(str);
-         }
-       }
-       i++;
+          str = xmlGetProp(pt_node, (const xmlChar *) "x");
+          if (str) {
+            pt.x = g_ascii_strtod ((char *) str, NULL);
+            xmlFree(str);
+          }
+          str = xmlGetProp (pt_node, (const xmlChar *) "y");
+          if (str) {
+            pt.y = g_ascii_strtod ((char *) str, NULL);
+            xmlFree(str);
+          }
+          g_array_append_val (arr, pt);
+          str = xmlGetProp (pt_node, (const xmlChar *) "main");
+          if (str && str[0] != '\0') {
+            if (info->main_cp != -1) {
+              message_warning ("More than one main connection point in %s.  Only the first one will be 
used.\n",
+                               info->name);
+            } else {
+              info->main_cp = i;
+            }
+            xmlFree (str);
+          }
+        }
+        i++;
       }
       info->nconnections = arr->len;
       info->connections = (Point *)arr->data;
diff --git a/objects/custom/shape_typeinfo.c b/objects/custom/shape_typeinfo.c
index 1a8903ee..e0b539a5 100644
--- a/objects/custom/shape_typeinfo.c
+++ b/objects/custom/shape_typeinfo.c
@@ -100,24 +100,24 @@ _characters (void *ctx,
   if (READ_DONE == context->state)
     /* no more to do */;
   if (READ_NAME == context->state) {
-    gchar *prev = context->si->name;
-    if (!prev)
-      context->si->name = g_strndup ((const gchar*)ch, len);
-    else {
-      gchar *now = g_strndup ((const gchar*)ch, len);
+    char *prev = context->si->name;
+    if (!prev) {
+      context->si->name = g_strndup ((const char*) ch, len);
+    } else {
+      char *now = g_strndup ((const char*) ch, len);
       context->si->name = g_strconcat (prev, now, NULL);
-      g_free (prev);
-      g_free (now);
+      g_clear_pointer (&prev, g_free);
+      g_clear_pointer (&now, g_free);
     }
   } else if (READ_ICON == context->state) {
-    gchar *prev = context->si->icon;
-    if (!prev)
+    char *prev = context->si->icon;
+    if (!prev) {
       context->si->icon = g_strndup ((const char*)ch, len);
-    else {
-      gchar *now = g_strndup ((const char*)ch, len);
+    } else {
+      char *now = g_strndup ((const char*)ch, len);
       context->si->icon = g_strconcat (prev, now, NULL);
-      g_free (prev);
-      g_free (now);
+      g_clear_pointer (&prev, g_free);
+      g_clear_pointer (&now, g_free);
     }
   }
 }
@@ -228,10 +228,10 @@ shape_typeinfo_load (ShapeInfo* info)
   }
   fclose (f);
   if (ctx.state == READ_DONE) {
-    gchar* tmp = info->icon;
+    char *tmp = info->icon;
     if (tmp) {
       info->icon = custom_get_relative_filename (info->filename, tmp);
-      g_free (tmp);
+      g_clear_pointer (&tmp, g_free);
     }
     return TRUE;
   } else {
diff --git a/objects/custom_lines/custom_lines.c b/objects/custom_lines/custom_lines.c
index 05916300..372d939b 100644
--- a/objects/custom_lines/custom_lines.c
+++ b/objects/custom_lines/custom_lines.c
@@ -43,12 +43,12 @@
 
 char* custom_lines_string_plus( char* lhs, char* mid, char* rhs );
 
-G_MODULE_EXPORT gboolean custom_linefile_load(gchar *filename, LineInfo **info);
+G_MODULE_EXPORT gboolean custom_linefile_load (char *filename, LineInfo **info);
 
 /* Cannot be static, because we may use this fn later when loading
    a new shape via the sheets dialog */
-   
-G_MODULE_EXPORT gboolean custom_linefile_load(gchar *filename, LineInfo **info)
+
+G_MODULE_EXPORT gboolean custom_linefile_load (char *filename, LineInfo **info)
 {
   if (!filename)
     return FALSE;
@@ -88,51 +88,51 @@ void custom_linetype_create_and_register( LineInfo* info )
         /* split at the file extension */
         char** chunks = g_strsplit( info->icon_filename, ".png", 0 );
         char buf[20];
-        
+
         sprintf( buf, "_%s", custom_linetype_strings[i] );
-        cloned_info->icon_filename = 
+        cloned_info->icon_filename =
           custom_lines_string_plus( chunks[0], buf, ".png" );
       }
 
       custom_linetype_new(cloned_info, &otype);
-      g_assert(otype); 
+      g_assert(otype);
       g_assert(otype->default_user_data);
       object_register_type(otype);
     }
   } else {
     custom_linetype_new(info, &otype);
-    g_assert(otype); 
+    g_assert(otype);
     g_assert(otype->default_user_data);
     object_register_type(otype);
   }
 }
 
-static void load_linefiles_from_tree(const gchar *directory)
+static void load_linefiles_from_tree (const char *directory)
 {
   GDir *dp;
   const char *dentry;
-  
+
   dp = g_dir_open(directory, 0, NULL);
   if (dp == NULL) {
     return;
   }
-  while ( (dentry = g_dir_read_name(dp)) ) {
-    gchar *filename = g_strconcat(directory, G_DIR_SEPARATOR_S,
-                                 dentry, NULL);
-    const gchar *p;
+
+  while ((dentry = g_dir_read_name (dp))) {
+    char *filename = g_build_filename (directory, dentry, NULL);
+    const char *p;
 
     if (g_file_test(filename, G_FILE_TEST_IS_DIR)) {
       load_linefiles_from_tree(filename);
-      g_free(filename);
+      g_clear_pointer (&filename, g_free);
       continue;
     }
     /* if it's not a directory, then it must be a .line file */
     if (   !g_file_test(filename, G_FILE_TEST_IS_REGULAR)
         || (strlen(dentry) < strlen( ".line" ))) {
-      g_free(filename);
+      g_clear_pointer (&filename, g_free);
       continue;
     }
-    
+
     p = dentry + strlen(dentry) - strlen( ".line" );
     if (0==strcmp(".line",p)) {
       LineInfo *info;
@@ -143,45 +143,45 @@ static void load_linefiles_from_tree(const gchar *directory)
         custom_linetype_create_and_register( info );
       }
     }
-    g_free(filename);
+    g_clear_pointer (&filename, g_free);
   }
   g_dir_close(dp);
 }
 
 DIA_PLUGIN_CHECK_INIT
 
+
 PluginInitResult
-dia_plugin_init(PluginInfo *info)
+dia_plugin_init (PluginInfo *info)
 {
   char *line_path;
-  const char *home_dir;
-  
-  
+  char *home_dir;
+
   if (!dia_plugin_info_init(info, _("CustomLines"), _("Custom XML lines loader"),
                            NULL, NULL))
     return DIA_PLUGIN_INIT_ERROR;
-  
-  home_dir = g_get_home_dir();
-  if (home_dir) {
-    home_dir = dia_config_filename("lines");
-    load_linefiles_from_tree(home_dir);
-    g_free((char *)home_dir);
+
+  if (g_get_home_dir ()) {
+    home_dir = dia_config_filename ("lines");
+    load_linefiles_from_tree (home_dir);
+    g_clear_pointer (&home_dir, g_free);
   }
 
   line_path = getenv("DIA_LINE_PATH");
   if (line_path) {
-    char **dirs = g_strsplit(line_path, G_SEARCHPATH_SEPARATOR_S, 0);
+    char **dirs = g_strsplit (line_path, G_SEARCHPATH_SEPARATOR_S, 0);
     int i;
 
-    for (i = 0; dirs[i] != NULL; i++)
-      load_linefiles_from_tree(dirs[i]);
+    for (i = 0; dirs[i] != NULL; i++) {
+      load_linefiles_from_tree (dirs[i]);
+    }
     g_strfreev(dirs);
   } else {
     char *thedir = dia_get_data_directory("lines");
-    load_linefiles_from_tree(thedir);
-    g_free(thedir);
+    load_linefiles_from_tree (thedir);
+    g_clear_pointer (&thedir, g_free);
   }
-  
+
   return DIA_PLUGIN_INIT_OK;
 }
 
diff --git a/objects/custom_lines/line_info.c b/objects/custom_lines/line_info.c
index 64d31ace..42a708c3 100644
--- a/objects/custom_lines/line_info.c
+++ b/objects/custom_lines/line_info.c
@@ -58,7 +58,7 @@ custom_get_relative_filename(const gchar *current, const gchar *relative)
     return g_strdup(relative);
   dirname = g_path_get_dirname(current);
   tmp = g_build_filename(dirname, relative, NULL);
-  g_free(dirname);
+  g_clear_pointer (&dirname, g_free);
   return tmp;
 }
 
@@ -345,13 +345,13 @@ line_info_load_and_apply_from_xmlfile(const gchar *filename, LineInfo* info)
       continue;
     else if (!strcmp((char*)node->name, "name")) {
       tmp = xmlNodeGetContent(node);
-/*      g_free(info->name);*/
+/*      g_clear_pointer (&info->name, g_free);*/
       info->name = g_strdup((char*)tmp);
 /*       fprintf( stderr, "New shape of type: `%s'\n", info->name ); */
       xmlFree(tmp);
     } else if ( !strcmp((char*)node->name, "icon")) {
       tmp = xmlNodeGetContent(node);
-      g_free(info->icon_filename);
+      g_clear_pointer (&info->icon_filename, g_free);
       info->icon_filename = custom_get_relative_filename(filename, (char*)tmp);
       xmlFree(tmp);
     } else if ( !strcmp((char*)node->name, "type")) {
diff --git a/objects/network/bus.c b/objects/network/bus.c
index 39de9a93..b183764b 100644
--- a/objects/network/bus.c
+++ b/objects/network/bus.c
@@ -377,11 +377,12 @@ static void
 bus_destroy(Bus *bus)
 {
   int i;
-  connection_destroy(&bus->connection);
-  for (i=0;i<bus->num_handles;i++)
-    g_free(bus->handles[i]);
-  g_free(bus->handles);
-  g_free(bus->parallel_points);
+  connection_destroy (&bus->connection);
+  for (i=0;i<bus->num_handles;i++) {
+    g_clear_pointer (&bus->handles[i], g_free);
+  }
+  g_clear_pointer (&bus->handles, g_free);
+  g_clear_pointer (&bus->parallel_points, g_free);
 }
 
 static DiaObject *
@@ -695,9 +696,7 @@ bus_change_free(struct PointChange *change)
 {
   if ( (change->type==TYPE_ADD_POINT && !change->applied) ||
        (change->type==TYPE_REMOVE_POINT && change->applied) ){
-    if (change->handle)
-      g_free(change->handle);
-    change->handle = NULL;
+    g_clear_pointer (&change->handle, g_free);
   }
 }
 
diff --git a/objects/standard/arc.c b/objects/standard/arc.c
index 15540534..5d477bb4 100644
--- a/objects/standard/arc.c
+++ b/objects/standard/arc.c
@@ -734,8 +734,7 @@ arc_create(Point *startpoint,
 static void
 arc_destroy(Arc *arc)
 {
-  g_free (arc->connection.object.enclosing_box);
-  arc->connection.object.enclosing_box = NULL;
+  g_clear_pointer (&arc->connection.object.enclosing_box, g_free);
   connection_destroy(&arc->connection);
 }
 
diff --git a/objects/standard/bezier.c b/objects/standard/bezier.c
index 3420fe1b..66a2d125 100644
--- a/objects/standard/bezier.c
+++ b/objects/standard/bezier.c
@@ -486,8 +486,7 @@ bezierline_create(Point *startpoint,
 static void
 bezierline_destroy(Bezierline *bezierline)
 {
-  g_free (bezierline->bez.object.enclosing_box);
-  bezierline->bez.object.enclosing_box = NULL;
+  g_clear_pointer (&bezierline->bez.object.enclosing_box, g_free);
   bezierconn_destroy(&bezierline->bez);
 }
 
diff --git a/objects/standard/beziergon.c b/objects/standard/beziergon.c
index 8c5718f1..c944310d 100644
--- a/objects/standard/beziergon.c
+++ b/objects/standard/beziergon.c
@@ -307,16 +307,16 @@ beziergon_create(Point *startpoint,
   return &beziergon->bezier.object;
 }
 
+
 static void
 beziergon_destroy(Beziergon *beziergon)
 {
-  if (beziergon->pattern)
-    g_object_unref (beziergon->pattern);
-  g_free (beziergon->bezier.object.enclosing_box);
-  beziergon->bezier.object.enclosing_box = NULL;
-  beziershape_destroy(&beziergon->bezier);
+  g_clear_object (&beziergon->pattern);
+  g_clear_pointer (&beziergon->bezier.object.enclosing_box, g_free);
+  beziershape_destroy (&beziergon->bezier);
 }
 
+
 static DiaObject *
 beziergon_copy(Beziergon *beziergon)
 {
diff --git a/objects/standard/box.c b/objects/standard/box.c
index abe3e57a..47c17e81 100644
--- a/objects/standard/box.c
+++ b/objects/standard/box.c
@@ -517,14 +517,15 @@ box_create(Point *startpoint,
   return &box->element.object;
 }
 
+
 static void
 box_destroy(Box *box)
 {
-  if (box->pattern)
-    g_object_unref (box->pattern);
-  element_destroy(&box->element);
+  g_clear_object (&box->pattern);
+  element_destroy (&box->element);
 }
 
+
 static DiaObject *
 box_copy(Box *box)
 {
diff --git a/objects/standard/ellipse.c b/objects/standard/ellipse.c
index a29942ca..3d681ef8 100644
--- a/objects/standard/ellipse.c
+++ b/objects/standard/ellipse.c
@@ -536,14 +536,15 @@ ellipse_create(Point *startpoint,
   return &ellipse->element.object;
 }
 
+
 static void
 ellipse_destroy(Ellipse *ellipse)
 {
-  if (ellipse->pattern)
-    g_object_unref (ellipse->pattern);
-  element_destroy(&ellipse->element);
+  g_clear_object (&ellipse->pattern);
+  element_destroy (&ellipse->element);
 }
 
+
 static DiaObject *
 ellipse_copy(Ellipse *ellipse)
 {
diff --git a/objects/standard/image.c b/objects/standard/image.c
index 194122d4..f000d27e 100644
--- a/objects/standard/image.c
+++ b/objects/standard/image.c
@@ -247,8 +247,7 @@ image_set_props(Image *image, GPtrArray *props)
       DiaImage *old_image = image->image;
       image->image = dia_image_new_from_pixbuf (image->pixbuf);
       image->pixbuf = g_object_ref ((GdkPixbuf *)dia_image_pixbuf (image->image));
-      if (old_image)
-        g_object_unref (old_image);
+      g_clear_object (&old_image);
       image->inline_data = TRUE;
     } else {
       image->inline_data = FALSE;
@@ -264,9 +263,7 @@ image_set_props(Image *image, GPtrArray *props)
     }
     if (!image->inline_data) {
       /* drop the pixbuf reference */
-      if (image->pixbuf)
-        g_object_unref (image->pixbuf);
-      image->pixbuf = NULL;
+      g_clear_object (&image->pixbuf);
     }
   } else if (   image->file && strlen(image->file) > 0
             && (   (!old_file || (strcmp (old_file, image->file) != 0))
@@ -293,7 +290,7 @@ image_set_props(Image *image, GPtrArray *props)
                 image->file ? image->file : "",
                 image->pixbuf, image->inline_data ? "TRUE" : "FALSE");
   }
-  g_free(old_file);
+  g_clear_pointer (&old_file, g_free);
   /* remember modification time */
   image->mtime = mtime;
 
@@ -654,21 +651,19 @@ image_create(Point *startpoint,
   return &image->element.object;
 }
 
+
 static void
-image_destroy(Image *image)
+image_destroy (Image *image)
 {
-  if (image->file != NULL)
-    g_free(image->file);
-
-  if (image->image != NULL)
-    dia_image_unref(image->image);
+  g_clear_pointer (&image->file, g_free);
 
-  if (image->pixbuf != NULL)
-    g_object_unref(image->pixbuf);
+  g_clear_object (&image->image);
+  g_clear_object (&image->pixbuf);
 
-  element_destroy(&image->element);
+  element_destroy (&image->element);
 }
 
+
 static DiaObject *
 image_copy(Image *image)
 {
@@ -753,7 +748,7 @@ image_save(Image *image, ObjectNode obj_node, DiaContext *ctx)
     if (relative) {
       /* The image pathname has the diagram file pathname in the beginning */
       data_add_filename(new_attribute(obj_node, "file"), relative, ctx);
-      g_free (relative);
+      g_clear_pointer (&relative, g_free);
     } else {
       /* Save the absolute path: */
       data_add_filename(new_attribute(obj_node, "file"), image->file, ctx);
@@ -855,18 +850,18 @@ image_load(ObjectNode obj_node, int version, DiaContext *ctx)
 
       image->image = dia_image_load(image_filename);
       if (image->image != NULL) {
-       /* Found file in same directory as diagram. */
-       g_free(image->file);
-       image->file = image_filename;
+        /* Found file in same directory as diagram. */
+        g_clear_pointer (&image->file, g_free);
+        image->file = image_filename;
       } else {
-       /* not found as relative path, try literally */
-       g_free (image_filename);
-
-       image->image = dia_image_load(image->file);
-       if (image->image == NULL) {
-         /* Didn't find file in current directory. */
-         dia_context_add_message (ctx, _("The image file '%s' was not found.\n"), image->file);
-       }
+        /* not found as relative path, try literally */
+        g_clear_pointer (&image_filename, g_free);
+
+        image->image = dia_image_load(image->file);
+        if (image->image == NULL) {
+          /* Didn't find file in current directory. */
+          dia_context_add_message (ctx, _("The image file '%s' was not found.\n"), image->file);
+        }
       }
     }
   }
@@ -877,10 +872,10 @@ image_load(ObjectNode obj_node, int version, DiaContext *ctx)
       GdkPixbuf *pixbuf = data_pixbuf (attribute_first_data(attr), ctx);
 
       if (pixbuf) {
-       image->image = dia_image_new_from_pixbuf (pixbuf);
-       image->inline_data = TRUE; /* avoid loosing it */
-       /* FIXME: should we reset the filename? */
-       g_object_unref (pixbuf);
+        image->image = dia_image_new_from_pixbuf (pixbuf);
+        image->inline_data = TRUE; /* avoid loosing it */
+        /* FIXME: should we reset the filename? */
+        g_clear_object (&pixbuf);
       }
     }
   } else {
diff --git a/objects/standard/outline.c b/objects/standard/outline.c
index 33e09045..c6179a7e 100644
--- a/objects/standard/outline.c
+++ b/objects/standard/outline.c
@@ -564,7 +564,7 @@ outline_destroy (Outline *outline)
 {
   if (outline->path)
     cairo_path_destroy (outline->path);
-  g_free (outline->name);
+  g_clear_pointer (&outline->name, g_free);
   object_destroy(&outline->object);
   /* but not the object itself? */
 }
diff --git a/objects/standard/polygon.c b/objects/standard/polygon.c
index 9bf4df9f..eb3f5dba 100644
--- a/objects/standard/polygon.c
+++ b/objects/standard/polygon.c
@@ -295,14 +295,15 @@ polygon_create(Point *startpoint,
   return &polygon->poly.object;
 }
 
+
 static void
 polygon_destroy(Polygon *polygon)
 {
-  if (polygon->pattern)
-    g_object_unref (polygon->pattern);
-  polyshape_destroy(&polygon->poly);
+  g_clear_object (&polygon->pattern);
+  polyshape_destroy (&polygon->poly);
 }
 
+
 static DiaObject *
 polygon_copy(Polygon *polygon)
 {
diff --git a/objects/standard/textobj.c b/objects/standard/textobj.c
index e24fb318..932b0496 100644
--- a/objects/standard/textobj.c
+++ b/objects/standard/textobj.c
@@ -469,8 +469,7 @@ static void
 textobj_destroy(Textobj *textobj)
 {
   text_destroy(textobj->text);
-  g_free (textobj->object.enclosing_box);
-  textobj->object.enclosing_box = NULL;
+  g_clear_pointer (&textobj->object.enclosing_box, g_free);
   object_destroy(&textobj->object);
 }
 
diff --git a/objects/standard/zigzagline.c b/objects/standard/zigzagline.c
index e0af6e47..2062ee7a 100644
--- a/objects/standard/zigzagline.c
+++ b/objects/standard/zigzagline.c
@@ -434,7 +434,7 @@ _convert_to_bezierline_callback (DiaObject *obj, Point *clicked, gpointer data)
     }
   }
   bezier = create_standard_bezierline(num_points, bp, &zigzagline->end_arrow, &zigzagline->start_arrow);
-  g_free(bp);
+  g_clear_pointer (&bp, g_free);
 
   return object_substitute (obj, bezier);
 }
diff --git a/plug-ins/cgm/cgm.c b/plug-ins/cgm/cgm.c
index d897c2ea..17bb28bf 100644
--- a/plug-ins/cgm/cgm.c
+++ b/plug-ins/cgm/cgm.c
@@ -1208,14 +1208,14 @@ export_cgm(DiagramData *data, DiaContext *ctx,
     write_real(file, 0.0);
     write_real(file, 0.0);
 
-    init_attributes(renderer);
+  init_attributes (renderer);
 
-    data_render (data, DIA_RENDERER(renderer), NULL, NULL, NULL);
+  data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
 
-    g_clear_object (&renderer->font);
-    g_object_unref (renderer);
+  g_clear_object (&renderer->font);
+  g_clear_object (&renderer);
 
-    return TRUE;
+  return TRUE;
 }
 
 /* GObject stuff */
diff --git a/plug-ins/drs/dia-render-script-import.c b/plug-ins/drs/dia-render-script-import.c
index bd4aa2ab..fff5a885 100644
--- a/plug-ins/drs/dia-render-script-import.c
+++ b/plug-ins/drs/dia-render-script-import.c
@@ -370,15 +370,19 @@ _render_object (xmlNodePtr render, DiaContext *ctx)
       } else if (node->type == XML_ELEMENT_NODE) {
         g_warning ("%s not handled", node->name);
       }
-      g_free (fill);
-      g_free (stroke);
+      g_clear_pointer (&fill, g_free);
+      g_clear_pointer (&stroke, g_free);
     }
   }
+
   o = dia_import_renderer_get_objects (ir);
-  g_object_unref (ir);
+
+  g_clear_object (&ir);
+
   return o;
 }
 
+
 static xmlNodePtr
 find_child_named (xmlNodePtr node, const char *name)
 {
diff --git a/plug-ins/drs/dia-render-script-renderer.c b/plug-ins/drs/dia-render-script-renderer.c
index 684814b5..f77929eb 100644
--- a/plug-ins/drs/dia-render-script-renderer.c
+++ b/plug-ins/drs/dia-render-script-renderer.c
@@ -80,7 +80,7 @@ set_font (DiaRenderer *self, DiaFont *font, real height)
   _node_set_real (node, "size", dia_font_get_size (font));
   _node_set_real (node, "height", height);
 
-  g_free (desc);
+  g_clear_pointer (&desc, g_free);
 }
 
 static void
@@ -233,11 +233,13 @@ draw_object (DiaRenderer *self,
   }
   renderer->root = g_queue_pop_tail (renderer->parents);
 
-  if (matrix)
+  if (matrix) {
     g_queue_pop_tail (renderer->matrices);
+  }
+
   /* one lost demand destruction */
   if (renderer->transformer && g_queue_is_empty (renderer->matrices)) {
-    g_object_unref (renderer->transformer);
+    g_clear_object (&renderer->transformer);
     renderer->transformer = NULL;
   }
 }
@@ -275,10 +277,12 @@ _node_set_color (xmlNodePtr node, const char *name, const Color *color)
   gchar *value;
 
   value = g_strdup_printf ("#%02x%02x%02x%02x",
-                          (int)(255*color->red), (int)(255*color->green),
-                          (int)(255*color->blue), (int)(255*color->alpha));
-  xmlSetProp(node, (const xmlChar *)name, (xmlChar *)value);
-  g_free (value);
+                           (int) (255 * color->red),
+                           (int) (255 * color->green),
+                           (int) (255 * color->blue),
+                           (int) (255 * color->alpha));
+  xmlSetProp (node, (const xmlChar *) name, (xmlChar *) value);
+  g_clear_pointer (&value, g_free);
 }
 
 static void
@@ -756,7 +760,7 @@ draw_image(DiaRenderer *self,
   uri = g_filename_to_uri (dia_image_filename(image), NULL, NULL);
   if (uri)
     xmlSetProp (node, (const xmlChar *)"uri", (xmlChar *) uri);
-  g_free (uri);
+  g_clear_pointer (&uri, g_free);
 }
 
 static void
diff --git a/plug-ins/drs/dia-render-script.c b/plug-ins/drs/dia-render-script.c
index 942b143f..e33a624e 100644
--- a/plug-ins/drs/dia-render-script.c
+++ b/plug-ins/drs/dia-render-script.c
@@ -151,11 +151,11 @@ export_data(DiagramData *data, DiaContext *ctx,
 
   drs_data_render(data, DIA_RENDERER(renderer));
 
-  xmlSetDocCompressMode(doc, 1);
-  xmlDiaSaveFile(filename, doc);
-  xmlFreeDoc(doc);
+  xmlSetDocCompressMode (doc, 1);
+  xmlDiaSaveFile (filename, doc);
+  xmlFreeDoc (doc);
 
-  g_object_unref(renderer);
+  g_clear_object (&renderer);
 
   return TRUE;
 }
diff --git a/plug-ins/dxf/dxf-export.c b/plug-ins/dxf/dxf-export.c
index f1c851ac..ce228ae3 100644
--- a/plug-ins/dxf/dxf-export.c
+++ b/plug-ins/dxf/dxf-export.c
@@ -626,13 +626,14 @@ export_dxf(DiagramData *data, DiaContext *ctx,
         dia_layer_render (layer, DIA_RENDERER (renderer), NULL, NULL, data, 0);
     }
 
-    dia_renderer_end_render (DIA_RENDERER (renderer));
+  dia_renderer_end_render (DIA_RENDERER (renderer));
 
-    g_object_unref (renderer);
+  g_clear_object (&renderer);
 
-    return TRUE;
+  return TRUE;
 }
 
+
 static const gchar *extensions[] = { "dxf", NULL };
 DiaExportFilter dxf_export_filter = {
     N_("Drawing Interchange File"),
diff --git a/plug-ins/dxf/dxf-import.c b/plug-ins/dxf/dxf-import.c
index 90b58150..155acc8e 100644
--- a/plug-ins/dxf/dxf-import.c
+++ b/plug-ins/dxf/dxf-import.c
@@ -556,7 +556,7 @@ read_entity_polyline_dxf (FILE *filedxf, DxfData *data, DiagramData *dia)
 
   memcpy (pcd->points, p, sizeof (Point) * pcd->num_points);
 
-  g_free (p);
+  g_clear_pointer (&p, g_free);
 
   polyline_obj = otype->ops->create (NULL, pcd, &h1, &h2);
 
@@ -976,7 +976,7 @@ read_entity_text_dxf (FILE *filedxf, DxfData *data, DiagramData *dia)
   g_return_val_if_fail (props->len == 1, NULL);
 
   tprop = g_ptr_array_index (props, 0);
-  g_free (tprop->text_data);
+  g_clear_pointer (&tprop->text_data, g_free);
   tprop->text_data = textvalue;
   tprop->attr.alignment = textalignment;
   tprop->attr.position.x = location.x;
@@ -1302,48 +1302,55 @@ read_section_blocks_dxf(FILE *filedxf, DxfData *data, DiagramData *dia)
     } while((data->code != 0) || (strcmp(data->value, "ENDSEC") != 0));
 }
 
+
 /* imports the given dxf-file, returns TRUE if successful */
 static gboolean
-import_dxf(const gchar *filename, DiagramData *dia, DiaContext *ctx, void* user_data)
+import_dxf (const char  *filename,
+            DiagramData *dia,
+            DiaContext  *ctx,
+            void        *user_data)
 {
-    FILE *filedxf;
-    DxfData *data;
+  FILE *filedxf;
+  DxfData *data;
+
+  filedxf = g_fopen (filename,"r");
+  if (filedxf == NULL){
+    dia_context_add_message (ctx,
+                             _("Couldn't open: '%s' for reading.\n"),
+                             dia_context_get_filename (ctx));
+    return FALSE;
+  }
 
-    filedxf = g_fopen(filename,"r");
-    if(filedxf == NULL){
-        dia_context_add_message(ctx, _("Couldn't open: '%s' for reading.\n"),
-                               dia_context_get_filename (ctx));
-        return FALSE;
-    }
+  data = g_new0 (DxfData, 1);
 
-    data = g_new(DxfData, 1);
+  do {
+    if (read_dxf_codes (filedxf, data) == FALSE) {
+      g_clear_pointer (&data, g_free);
+      dia_context_add_message (ctx,
+                                _("read_dxf_codes failed on '%s'"),
+                                dia_context_get_filename (ctx));
+        return FALSE;
+    } else {
+      if (0 == data->code && strstr (data->codeline, "AutoCAD Binary DXF")) {
+        g_clear_pointer (&data, g_free);
+        dia_context_add_message (ctx,
+                                  _("Binary DXF from '%s' not supported"),
+                                  dia_context_get_filename (ctx));
+        return FALSE;
+      }
 
-    do {
-        if(read_dxf_codes(filedxf, data) == FALSE) {
-            g_free(data);
-           dia_context_add_message(ctx, _("read_dxf_codes failed on '%s'"),
-                                   dia_context_get_filename(ctx) );
-            return FALSE;
+      if (0 == data->code) {
+        if (strcmp (data->value, "SECTION") == 0) {
+          /* don't think we need to do anything */
+        } else if (strcmp (data->value, "ENDSEC") == 0) {
+          /* don't think we need to do anything */
+        } else if (strcmp (data->value, "EOF") == 0) {
+          /* handled below */
+        } else {
+          g_printerr ("DXF 0:%s not handled\n", data->value);
         }
-        else {
-            if (0 == data->code && strstr(data->codeline, "AutoCAD Binary DXF")) {
-                g_free(data);
-               dia_context_add_message(ctx, _("Binary DXF from '%s' not supported"),
-                                       dia_context_get_filename(ctx));
-                return FALSE;
-            }
-           if (0 == data->code) {
-                if(strcmp(data->value, "SECTION") == 0) {
-                 /* don't think we need to do anything */
-                } else if(strcmp(data->value, "ENDSEC") == 0) {
-                 /* don't think we need to do anything */
-                } else if(strcmp(data->value, "EOF") == 0) {
-                 /* handled below */
-               } else {
-                 g_printerr ("DXF 0:%s not handled\n", data->value);
-               }
-            } else if(data->code == 2) {
-                if(strcmp(data->value, "ENTITIES") == 0) {
+      } else if (data->code == 2) {
+        if (strcmp (data->value, "ENTITIES") == 0) {
                   /*printf( "reading section entities\n" );*/
                     read_section_entities_dxf(filedxf, data, dia);
                 }
@@ -1375,7 +1382,7 @@ import_dxf(const gchar *filename, DiagramData *dia, DiaContext *ctx, void* user_
         }
     }while((data->code != 0) || (strcmp(data->value, "EOF") != 0));
 
-    g_free(data);
+    g_clear_pointer (&data, g_free);
     if (_color_by_layer_ht) {
         g_hash_table_destroy (_color_by_layer_ht);
         _color_by_layer_ht = NULL;
diff --git a/plug-ins/hpgl/hpgl.c b/plug-ins/hpgl/hpgl.c
index 194088ee..e3536a48 100644
--- a/plug-ins/hpgl/hpgl.c
+++ b/plug-ins/hpgl/hpgl.c
@@ -766,11 +766,11 @@ export_data(DiagramData *data, DiaContext *ctx,
             hpgl_scale(renderer, extent->bottom),
             hpgl_scale(renderer, extent->top));
 #endif
-    data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
+  data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
 
-    g_object_unref(renderer);
+  g_clear_object (&renderer);
 
-    return TRUE;
+  return TRUE;
 }
 
 static const gchar *extensions[] = { "plt", "hpgl", NULL };
diff --git a/plug-ins/metapost/render_metapost.c b/plug-ins/metapost/render_metapost.c
index b9088f62..e20b7a97 100644
--- a/plug-ins/metapost/render_metapost.c
+++ b/plug-ins/metapost/render_metapost.c
@@ -944,8 +944,8 @@ draw_image(DiaRenderer *self,
         }
     }
 
-    g_free(mask_data);
-    g_free(rgb_data);
+    g_clear_pointer (&mask_data, g_free);
+    g_clear_pointer (&rgb_data, g_free);
 }
 
 /* GObject stuff */
@@ -1169,22 +1169,23 @@ export_metapost(DiagramData *data, DiaContext *ctx,
     fprintf(renderer->file,"  t = %s;\n\n",
            mp_dtostr(d1_buf, data->paper.scaling));
 
-    initial_color.red=0.;
-    initial_color.green=0.;
-    initial_color.blue=0.;
-    initial_color.alpha=1.;
-    set_line_color(renderer,&initial_color);
+  initial_color.red= 0.0;
+  initial_color.green= 0.0;
+  initial_color.blue= 0.0;
+  initial_color.alpha= 1.0;
+  set_line_color (renderer,&initial_color);
 
-    data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
+  data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
 
-    g_object_unref(renderer);
+  g_clear_object (&renderer);
 
-    return TRUE;
+  return TRUE;
 }
 
+
 static const gchar *extensions[] = { "mp", NULL };
 DiaExportFilter metapost_export_filter = {
-    N_("TeX Metapost macros"),
-    extensions,
-    export_metapost
+  N_("TeX Metapost macros"),
+  extensions,
+  export_metapost
 };
diff --git a/plug-ins/pgf/render_pgf.c b/plug-ins/pgf/render_pgf.c
index a416c435..f7781b6a 100644
--- a/plug-ins/pgf/render_pgf.c
+++ b/plug-ins/pgf/render_pgf.c
@@ -1322,7 +1322,7 @@ draw_string (DiaRenderer *self,
             pgf_dtostr (px_buf,pos->x),
             pgf_dtostr (py_buf,pos->y),
             escaped);
-  g_free (escaped);
+  g_clear_pointer (&escaped, g_free);
 }
 
 static void
@@ -1405,11 +1405,11 @@ export_pgf(DiagramData *data, DiaContext *ctx,
     initial_color.blue=1.;
     set_fill_color(renderer,&initial_color);
 
-    data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
+  data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
 
-    g_object_unref(renderer);
+  g_clear_object (&renderer);
 
-    return TRUE;
+  return TRUE;
 }
 
 static const gchar *extensions[] = { "tex", NULL };
diff --git a/plug-ins/pixbuf/pixbuf.c b/plug-ins/pixbuf/pixbuf.c
index aebdc7db..e6f8aa52 100644
--- a/plug-ins/pixbuf/pixbuf.c
+++ b/plug-ins/pixbuf/pixbuf.c
@@ -96,25 +96,21 @@ export_data(DiagramData *data, DiaContext *ctx,
                                            0, 0, 0, 0, width, height);
   }
   #endif
-  if (pixbuf)
-    {
-      gdk_pixbuf_save (pixbuf, filename, format, &error, NULL);
-      g_object_unref (pixbuf);
-    }
-  else
-    {
-      dia_context_add_message(ctx, _("Failed to create pixbuf from drawable."));
-    }
+  if (pixbuf) {
+    gdk_pixbuf_save (pixbuf, filename, format, &error, NULL);
+    g_clear_object (&pixbuf);
+  } else {
+    dia_context_add_message (ctx, _("Failed to create pixbuf from drawable."));
+  }
 
-  if (error)
-    {
-      dia_context_add_message(ctx, _("Could not save file:\n%s\n%s"),
-                             dia_context_get_filename(ctx),
-                             error->message);
-      g_error_free (error);
-    }
+  if (error) {
+    dia_context_add_message (ctx, _("Could not save file:\n%s\n%s"),
+                             dia_context_get_filename(ctx),
+                             error->message);
+    g_clear_error (&error);
+  }
 
-  g_object_unref (renderer);
+  g_clear_object (&renderer);
 
   return TRUE;
 }
@@ -183,19 +179,19 @@ _plugin_unload (PluginInfo *info)
   for (p = _import_filters; p != NULL; p = g_list_next(p)) {
     DiaImportFilter *ifilter = (DiaImportFilter *)p->data;
     filter_unregister_import (ifilter);
-    g_free ((gchar*)ifilter->description);
+    g_free ((char *) ifilter->description);
     g_strfreev ((gchar**)ifilter->extensions);
-    g_free ((gpointer)ifilter->user_data);
-    g_free ((gchar*)ifilter->unique_name);
+    g_clear_pointer (&ifilter->user_data, g_free);
+    g_free ((char *) ifilter->unique_name);
   }
   g_list_free (_import_filters);
   for (p = _export_filters; p != NULL; p = g_list_next(p)) {
     DiaExportFilter *efilter = p->data;
     filter_unregister_export (efilter);
-    g_free ((gchar*)efilter->description);
+    g_free ((char *) efilter->description);
     g_strfreev ((gchar**)efilter->extensions);
-    g_free ((gpointer)efilter->user_data);
-    g_free ((gchar*)efilter->unique_name);
+    g_clear_pointer (&efilter->user_data, g_free);
+    g_free ((char *) efilter->unique_name);
   }
   g_list_free (_export_filters);
 }
@@ -244,7 +240,7 @@ dia_plugin_init(PluginInfo *info)
           efilter->export_func = export_data;
           efilter->user_data = g_strdup (name);
           efilter->unique_name = g_strdup_printf ("pixbuf-%s", (gchar*)efilter->user_data);
-          g_free (name);
+          g_clear_pointer (&name, g_free);
           _export_filters = g_list_append (_export_filters, efilter);
           filter_register_export(efilter);
         }
@@ -266,7 +262,7 @@ dia_plugin_init(PluginInfo *info)
               || strcmp (name, "wbmp") == 0
               || strcmp (name, "xbm") == 0)
             {
-              g_free (name);
+              g_clear_pointer (&name, g_free);
               continue;
             }
          ifilter = g_new0 (DiaImportFilter, 1);
@@ -283,7 +279,7 @@ dia_plugin_init(PluginInfo *info)
              || strcmp (name, "wmf") == 0
              || strcmp (name, "emf") == 0)
            ifilter->hints = FILTER_DONT_GUESS;
-          g_free (name);
+          g_clear_pointer (&name, g_free);
           _import_filters = g_list_append (_import_filters, ifilter);
           filter_register_import(ifilter);
         }
diff --git a/plug-ins/postscript/diapsrenderer.c b/plug-ins/postscript/diapsrenderer.c
index 846c8d8f..b89f7dd5 100644
--- a/plug-ins/postscript/diapsrenderer.c
+++ b/plug-ins/postscript/diapsrenderer.c
@@ -613,7 +613,7 @@ ps_convert_string (const char *text, DiaContext *ctx)
       str++;
     }
   }
-  g_free (localestr);
+  g_clear_pointer (&localestr, g_free);
   return buffer;
 }
 
@@ -666,7 +666,7 @@ draw_string(DiaRenderer *self,
   buffer = ps_convert_string(text, renderer->ctx);
 
   fprintf(renderer->file, "(%s) ", buffer);
-  g_free(buffer);
+  g_clear_pointer (&buffer, g_free);
 
   pos_adj.x = pos->x;
   pos_adj.y = pos->y - dia_font_descent ("", renderer->font, renderer->font_height);
@@ -742,8 +742,8 @@ draw_image(DiaRenderer *self,
   fprintf(renderer->file, "gr\n");
   fprintf(renderer->file, "\n");
 
-  g_free(rgb_data);
-  g_free(mask_data);
+  g_clear_pointer (&rgb_data, g_free);
+  g_clear_pointer (&mask_data, g_free);
 }
 
 static void
@@ -1031,7 +1031,7 @@ dia_ps_renderer_finalize (GObject *object)
 {
   DiaPsRenderer *renderer = DIA_PS_RENDERER (object);
 
-  g_free(renderer->title);
+  g_clear_pointer (&renderer->title, g_free);
   g_clear_object (&renderer->font);
   /*  fclose(renderer->file);*/
 
diff --git a/plug-ins/postscript/paginate_psprint.c b/plug-ins/postscript/paginate_psprint.c
index 38d4fb97..dd47bed9 100644
--- a/plug-ins/postscript/paginate_psprint.c
+++ b/plug-ins/postscript/paginate_psprint.c
@@ -189,14 +189,14 @@ paginate_psprint(DiagramData *dia, FILE *file)
       page_bounds.top = y;
       page_bounds.bottom = y + height;
 
-      nobjs += print_page(dia,rend, &page_bounds);
+      nobjs += print_page (dia,rend, &page_bounds);
     }
   }
 
-  g_object_unref(rend);
-
+  g_clear_object (&rend);
 }
 
+
 static void
 change_entry_state(GtkToggleButton *radio, GtkWidget *entry)
 {
@@ -217,14 +217,15 @@ pipe_handler(int signum)
   sigpipe_received = TRUE;
 }
 
+
 static gboolean
-diagram_print_destroy(GtkWidget *widget)
+diagram_print_destroy (GtkWidget *widget)
 {
   DiagramData *dia;
 
-  if ((dia = g_object_get_data(G_OBJECT(widget), "diagram")) != NULL) {
-    g_object_unref(dia);
-    g_object_set_data(G_OBJECT(widget), "diagram", NULL);
+  if ((dia = g_object_get_data (G_OBJECT (widget), "diagram")) != NULL) {
+    g_clear_object (&dia);
+    g_object_set_data (G_OBJECT (widget), "diagram", NULL);
   }
 
   return FALSE;
@@ -340,7 +341,7 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
     }
 
     gtk_entry_set_text (GTK_ENTRY (cmd), printcmd);
-    g_free (printcmd);
+    g_clear_pointer (&printcmd, g_free);
     printcmd = NULL;
   }
 #endif
@@ -359,7 +360,7 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
   }
   printer_filename = strcat (printer_filename, ".ps");
   gtk_entry_set_text (GTK_ENTRY (ofile), printer_filename);
-  g_free (printer_filename);
+  g_clear_pointer (&printer_filename, g_free);
   orig_file = g_strdup (gtk_entry_get_text (GTK_ENTRY (ofile)));
 
   /* Scaling is already set at creation. */
@@ -383,8 +384,8 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
     if (!cont) {
       persistence_change_string_entry ("printer-command", orig_command, cmd);
       gtk_widget_destroy (dialog);
-      g_free (orig_command);
-      g_free (orig_file);
+      g_clear_pointer (&orig_command, g_free);
+      g_clear_pointer (&orig_file, g_free);
       return;
     }
 
@@ -425,7 +426,7 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
                                   _("The file '%s' already exists.\n"
                                     "Do you want to overwrite it?"),
                                   utf8filename);
-        g_free (utf8filename);
+        g_clear_pointer (&utf8filename, g_free);
         gtk_window_set_title (GTK_WINDOW (confirm_overwrite_dialog),
                               _("File already exists"));
         gtk_dialog_set_default_response (GTK_DIALOG (confirm_overwrite_dialog),
@@ -447,7 +448,7 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
           full_filename = g_build_filename (g_get_home_dir (),
                                             new_filename, NULL);
           file = g_fopen (full_filename, "w");
-          g_free (full_filename);
+          g_clear_pointer (&full_filename, g_free);
         } else {
           file = g_fopen (new_filename, "w");
         }
@@ -465,7 +466,7 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
         if (is_pipe) {
           message_warning (_("Could not run command '%s': %s"),
                            printcmd, strerror (errno));
-          g_free (printcmd);
+          g_clear_pointer (&printcmd, g_free);
         } else
           message_warning (_("Could not open '%s' for writing: %s"),
                            gtk_entry_get_text (GTK_ENTRY (ofile)),
@@ -475,8 +476,8 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
     }
   } while (!done);
 
-  g_free (orig_command);
-  g_free (orig_file);
+  g_clear_pointer (&orig_command, g_free);
+  g_clear_pointer (&orig_file, g_free);
 #ifndef G_OS_WIN32
   /* set up a SIGPIPE handler to catch IO errors, rather than segfaulting */
   sigpipe_received = FALSE;
@@ -507,6 +508,6 @@ diagram_print_ps (DiagramData *dia, const gchar* original_filename)
   }
 
   if (is_pipe) {
-    g_free (printcmd);
+    g_clear_pointer (&printcmd, g_free);
   }
 }
diff --git a/plug-ins/postscript/ps-utf8.c b/plug-ins/postscript/ps-utf8.c
index 3103b3d3..3b4f70af 100644
--- a/plug-ins/postscript/ps-utf8.c
+++ b/plug-ins/postscript/ps-utf8.c
@@ -2,11 +2,11 @@
  * Copyright (C) 1998 Alexander Larsson
  *
  * ps-utf8.c: builds custom Postscript encodings to write arbitrary utf8
- * strings and have the device understand what's going on. 
+ * strings and have the device understand what's going on.
  * Copyright (C) 2001 Cyrille Chepelov <chepelov calixo net>
- * 
- * Portions derived from Gnome-Print/gp-ps-unicode.c, written by 
- * Lauris Kaplinski <lauris helixcode com>, 
+ *
+ * Portions derived from Gnome-Print/gp-ps-unicode.c, written by
+ * Lauris Kaplinski <lauris helixcode com>,
  * Copyright (C) 1999-2000 Helix Code, Inc.
  *
  * This program is free software; you can redistribute it and/or modify
@@ -42,16 +42,16 @@ static void font_descriptor_destroy(PSFontDescriptor *fd);
 static void use_font(PSUnicoder *psu, PSFontDescriptor *fd);
 static PSEncodingPage *encoding_page_new(int num);
 static void encoding_page_destroy(PSEncodingPage *ep);
-static int encoding_page_add_unichar(PSEncodingPage *ep, 
+static int encoding_page_add_unichar(PSEncodingPage *ep,
                                      gunichar uchar);
 
 static void use_encoding(PSUnicoder *psu, PSEncodingPage *ep);
- 
+
 static void psu_add_encoding(PSUnicoder *psu, gunichar uchar);
 static void psu_make_new_encoding_page(PSUnicoder *psu);
 /* Unicoder functions */
 
-extern PSUnicoder *ps_unicoder_new(const PSUnicoderCallbacks *psucbk, 
+extern PSUnicoder *ps_unicoder_new(const PSUnicoderCallbacks *psucbk,
                                    gpointer usrdata)
 {
   PSUnicoder *psu = g_new0(PSUnicoder,1);
@@ -60,12 +60,12 @@ extern PSUnicoder *ps_unicoder_new(const PSUnicoderCallbacks *psucbk,
 
   psu->defined_fonts = g_hash_table_new(g_str_hash,g_str_equal);
   psu->unicode_to_page = g_hash_table_new(NULL,NULL);
-  
+
   psu_make_new_encoding_page(psu);
   return psu;
 }
 
-static gboolean 
+static gboolean
 ghrfunc_remove_font(gpointer key, gpointer value, gpointer user_data)
 {
   font_descriptor_destroy((PSFontDescriptor *)value);
@@ -89,10 +89,10 @@ extern void ps_unicoder_destroy(PSUnicoder *psu)
   g_slist_foreach(psu->encoding_pages,
                   gfunc_free_encoding_page,
                   NULL);
-  g_free(psu);
+  g_clear_pointer (&psu, g_free);
 }
 
-extern void 
+extern void
 psu_set_font_face(PSUnicoder *psu, const gchar *face, float size)
 {
   psu->face = face;
@@ -102,14 +102,14 @@ psu_set_font_face(PSUnicoder *psu, const gchar *face, float size)
 
 static void psu_make_new_encoding_page(PSUnicoder *psu)
 {
-  int num = 0;  
+  int num = 0;
   PSEncodingPage *ep;
 
   if (psu->last_page) num = psu->last_page->page_num + 1;
   ep = encoding_page_new(num);
   psu->last_page = ep;
   psu->encoding_pages = g_slist_append(psu->encoding_pages,ep);
-  
+
   if (num == 1) {
     g_warning("You are going to use more than %d different characters; dia will begin to \n"
               "heavily use encoding switching. This feature has never been tested; \n"
@@ -126,7 +126,7 @@ static void psu_add_encoding(PSUnicoder *psu, gunichar uchar)
   }
   if (!encoding_page_add_unichar(psu->last_page,uchar)) {
     psu_make_new_encoding_page(psu);
-    if (!encoding_page_add_unichar(psu->last_page,uchar)) 
+    if (!encoding_page_add_unichar(psu->last_page,uchar))
       {
        g_assert_not_reached();
       }
@@ -140,8 +140,8 @@ static void psu_add_encoding(PSUnicoder *psu, gunichar uchar)
   }
 }
 
-extern void 
-psu_check_string_encodings(PSUnicoder *psu, 
+extern void
+psu_check_string_encodings(PSUnicoder *psu,
                            const char *utf8_string)
 {
   gunichar uchar;
@@ -155,7 +155,7 @@ psu_check_string_encodings(PSUnicoder *psu,
     if ((uchar > 32) && (uchar < 2048)) {
       psu_add_encoding(psu,uchar);
     }
-  }  
+  }
 }
 
 #define BUFSIZE 256
@@ -175,10 +175,10 @@ static void psu_show_flush_buffer(const PSUnicoder *psu,
 }
 
 
-static void 
-encoded_psu_show_string(PSUnicoder *psu,
-                        const char *utf8_string,
-                        FlushFunc flushfunc)
+static void
+encoded_psu_show_string (PSUnicoder *psu,
+                         const char *utf8_string,
+                         FlushFunc   flushfunc)
 {
   gunichar uchar;
   gchar c;
@@ -194,13 +194,13 @@ encoded_psu_show_string(PSUnicoder *psu,
     len++;
 
     if (psu->current_encoding) {
-      c = 
+      c =
         (gchar)GPOINTER_TO_INT(g_hash_table_lookup(psu->current_encoding->backpage,
                                                    GINT_TO_POINTER(uchar)));
     } else {
       c = 0;
     }
-      
+
     if (!c) {
       /* No page or not the right page... switch ! */
       PSEncodingPage *ep = g_hash_table_lookup(psu->unicode_to_page,
@@ -211,7 +211,7 @@ encoded_psu_show_string(PSUnicoder *psu,
         c = (gchar)GPOINTER_TO_INT(g_hash_table_lookup(ep->backpage,
                                                        GINT_TO_POINTER(uchar)));
       } else {
-        c = 31; 
+        c = 31;
       }
 
       if ((!c)||(c==31)) {
@@ -221,27 +221,27 @@ encoded_psu_show_string(PSUnicoder *psu,
     }
     /* We now are in the right page, and c is the image of uchar with that
        encoding. */
-    
-    if ( ((!psu->current_font) || 
+
+    if ( ((!psu->current_font) ||
           (psu->current_font->encoding != psu->current_encoding))) {
       PSFontDescriptor *fd;
-      const gchar *font_name;
+      char *font_name;
       if (bufu) {
         psu_show_flush_buffer(psu,buf,&bufu,flushfunc,first);
         first = FALSE;
       }
 
-      font_name = make_font_descriptor_name(psu->face,
-                                            psu->current_encoding->name);
-      fd = g_hash_table_lookup(psu->defined_fonts,font_name);
+      font_name = make_font_descriptor_name (psu->face,
+                                             psu->current_encoding->name);
+      fd = g_hash_table_lookup (psu->defined_fonts, font_name);
       if (fd) {
-        g_free((gpointer)font_name);
+        g_clear_pointer (&font_name, g_free);
         font_name = fd->name;
       } else {
-        fd = font_descriptor_new(psu->face,
-                                 psu->current_encoding,
-                                 font_name);
-        g_free((gpointer)font_name);
+        fd = font_descriptor_new (psu->face,
+                                  psu->current_encoding,
+                                  font_name);
+        g_clear_pointer (&font_name, g_free);
         font_name = fd->name;
         g_hash_table_insert(psu->defined_fonts,(gpointer)font_name,fd);
       }
@@ -252,12 +252,12 @@ encoded_psu_show_string(PSUnicoder *psu,
       first = FALSE;
     }
     buf[bufu++] = c;
-  } 
+  }
   if ((bufu)||(!len)) /* even if !len, to avoid crashing the PS stack. */
     psu_show_flush_buffer(psu,buf,&bufu,flushfunc,first);
 }
 
-static void 
+static void
 symbol_psu_show_string(PSUnicoder *psu,
                         const char *utf8_string,
                         FlushFunc flushfunc)
@@ -318,7 +318,7 @@ symbol_psu_show_string(PSUnicoder *psu,
     psu_show_flush_buffer(psu,buf,&bufu,flushfunc,first);
 }
 
-static void 
+static void
 flush_show_string(const PSUnicoder *psu,
                   const gchar *buf,
                   gboolean first)
@@ -326,19 +326,19 @@ flush_show_string(const PSUnicoder *psu,
   psu->callbacks->show_string(psu->usrdata,buf);
 }
 
-extern void 
+extern void
 psu_show_string(PSUnicoder *psu,
                 const char *utf8_string)
 {
   if (0==strcmp(psu->face,"Symbol")) {
     symbol_psu_show_string(psu,utf8_string,&flush_show_string);
-  } else { 
+  } else {
     encoded_psu_show_string(psu,utf8_string,&flush_show_string);
   }
 }
 
 
-static void 
+static void
 flush_get_string_width(const PSUnicoder *psu,
                             const char *buf,
                             gboolean first)
@@ -346,13 +346,13 @@ flush_get_string_width(const PSUnicoder *psu,
   psu->callbacks->get_string_width(psu->usrdata,buf,first);
 }
 
-extern void 
+extern void
 psu_get_string_width(PSUnicoder *psu,
                      const char *utf8_string)
 {
   if (0==strcmp(psu->face,"Symbol")) {
     symbol_psu_show_string(psu,utf8_string,&flush_get_string_width);
-  } else { 
+  } else {
     encoded_psu_show_string(psu,utf8_string,&flush_get_string_width);
   }
 }
@@ -364,7 +364,7 @@ static PSEncodingPage *
 encoding_page_new(int num)
 {
   PSEncodingPage *ep = g_new0(PSEncodingPage,1);
-  
+
   ep->name = g_strdup_printf("e%d",num);
   ep->page_num = 0;
   ep->serial_num = 0;
@@ -374,36 +374,39 @@ encoding_page_new(int num)
   return ep;
 }
 
-static void encoding_page_destroy(PSEncodingPage *ep)
+
+static void
+encoding_page_destroy (PSEncodingPage *ep)
 {
-  g_free((gpointer)ep->name);
-  g_hash_table_destroy(ep->backpage);
-  g_free(ep);
+  g_clear_pointer (&ep->name, g_free);
+  g_hash_table_destroy (ep->backpage);
+  g_clear_pointer (&ep, g_free);
 }
 
-static int 
+
+static int
 encoding_page_add_unichar(PSEncodingPage *ep, gunichar uchar)
 {
   int res;
   if (ep->entries >= PSEPAGE_SIZE) return 0; /* page is full. */
-  
+
   while ((ep->entries == (')'-PSEPAGE_BEGIN)) ||
          (ep->entries == ('\\' - PSEPAGE_BEGIN)) ||
          (ep->entries == ('('-PSEPAGE_BEGIN))) ep->entries++;
 
   res = ep->entries++;
-  
+
   ep->page[res] = uchar;
-  
+
   res += PSEPAGE_BEGIN;
   g_hash_table_insert(ep->backpage,
                       GINT_TO_POINTER(uchar),GINT_TO_POINTER(res));
   ep->serial_num++;
   return res;
-  
+
 }
 
-static void 
+static void
 use_encoding(PSUnicoder *psu, PSEncodingPage *ep)
 {
   if (ep->serial_num != ep->last_realized) {
@@ -430,26 +433,28 @@ font_descriptor_new(const gchar *face,
                     const gchar *name)
 {
   PSFontDescriptor *fd = g_new(PSFontDescriptor,1);
-  
+
   fd->face = face;
   fd->encoding = encoding;
   fd->encoding_serial_num = -1;
 
-  if (name) 
+  if (name)
     fd->name = g_strdup(name);
   else
     fd->name = make_font_descriptor_name(face,encoding->name);
   return fd;
 }
 
-static void 
-font_descriptor_destroy(PSFontDescriptor *fd)
+
+static void
+font_descriptor_destroy (PSFontDescriptor *fd)
 {
-  g_free((gpointer)fd->name);
-  g_free(fd);
+  g_clear_pointer (&fd->name, g_free);
+  g_clear_pointer (&fd, g_free);
 }
 
-static void 
+
+static void
 use_font(PSUnicoder *psu, PSFontDescriptor *fd)
 {
   if (psu->current_font == fd) return; /* Already done. */
@@ -458,7 +463,7 @@ use_font(PSUnicoder *psu, PSFontDescriptor *fd)
     psu->callbacks->select_ps_font(psu->usrdata,fd->name,psu->size);
   } else {
     gboolean undef,define,select;
-  
+
     define = (fd->encoding->serial_num != fd->encoding_serial_num);
     undef = (define && (fd->encoding_serial_num <= 0));
     select = ((psu->current_font != fd) || (psu->current_size != psu->size));
diff --git a/plug-ins/postscript/ps-utf8.h b/plug-ins/postscript/ps-utf8.h
index e25eb944..c423c3ad 100644
--- a/plug-ins/postscript/ps-utf8.h
+++ b/plug-ins/postscript/ps-utf8.h
@@ -2,9 +2,9 @@
  * Copyright (C) 1998 Alexander Larsson
  *
  * ps-utf8.h: builds custom Postscript encodings to write arbitrary utf8
- * strings and have the device understand what's going on. 
+ * strings and have the device understand what's going on.
  * Copyright (C) 2001 Cyrille Chepelov <chepelov calixo net>
- * 
+ *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation; either version 2 of the License, or
@@ -37,13 +37,13 @@ typedef struct _PSUnicoderCallbacks PSUnicoderCallbacks;
 #define PSEPAGE_SIZE (256-PSEPAGE_BEGIN)
 
 struct _PSFontDescriptor {
-  const gchar *face; /* LE */
-  const gchar *name; /* LE */
+  const char *face; /* LE */
+  char *name; /* LE */
   const PSEncodingPage *encoding; /* DNLE */
   int encoding_serial_num; /* if encoding->serial_num > this, we have to
                               re-emit the font. If it's negative,
                               the font has never been emitted. */
-}; 
+};
 
 /* "defined_fonts" cache is simply a dictionary (g_hash_table):
        ("face-e%d-%f" % (encoding_page_#,size)) --> font descriptor
@@ -51,7 +51,7 @@ struct _PSFontDescriptor {
 */
 
 struct _PSEncodingPage {
-  const gchar *name; /* LE. */
+  char *name; /* LE. */
   int page_num;
   int serial_num;
   int last_realized;
@@ -64,7 +64,7 @@ struct _PSUnicoder {
   gpointer usrdata;
   const PSUnicoderCallbacks *callbacks;
 
-  const gchar *face;
+  const char *face;
   float size;
   float current_size; /* might lag a little... */
   PSFontDescriptor *current_font; /* DNLE */
@@ -76,26 +76,26 @@ struct _PSUnicoder {
   const PSEncodingPage *current_encoding; /* DNLE */
 };
 
-typedef void (*DestroyPSFontFunc)(gpointer usrdata, const gchar *fontname);
-typedef void (*BuildPSEncodingFunc)(gpointer usrdata, 
-                                    const gchar *name,
+typedef void (*DestroyPSFontFunc)(gpointer usrdata, const char *fontname);
+typedef void (*BuildPSEncodingFunc)(gpointer usrdata,
+                                    const char *name,
                                     const gunichar table[PSEPAGE_SIZE]);
-/* note: the first $PSEPAGE_BEGIN will always be /.notdef, likewise 
+/* note: the first $PSEPAGE_BEGIN will always be /.notdef, likewise
    for ( and ) */
-typedef void (*BuildPSFontFunc)(gpointer usrdata, 
-                                const gchar *name,
-                                const gchar *face,
-                                const gchar *encoding_name);
-/* must definefont a font under "fontname", with the "encname" encoding 
+typedef void (*BuildPSFontFunc)(gpointer usrdata,
+                                const char *name,
+                                const char *face,
+                                const char *encoding_name);
+/* must definefont a font under "fontname", with the "encname" encoding
    (already defined). */
-typedef void (*SelectPSFontFunc)(gpointer usrdata, 
-                                 const gchar *fontname,
+typedef void (*SelectPSFontFunc)(gpointer usrdata,
+                                 const char *fontname,
                                  float size);
 /* must select (setfont) an already found and defined font. */
-typedef void (*ShowStringFunc)(gpointer usrdata, const gchar *string);
+typedef void (*ShowStringFunc)(gpointer usrdata, const char *string);
 /* typically, does "(string) show" (but can do other things).
    string is guaranteed to not have escaping issues. */
-typedef void (*GetStringWidthFunc)(gpointer usrdata, const gchar *string,
+typedef void (*GetStringWidthFunc)(gpointer usrdata, const char *string,
                                gboolean first);
 /* gets the string width on the PS stack. if !first, adds it to the previous
    element of the stack. */
@@ -108,16 +108,16 @@ struct _PSUnicoderCallbacks {
   ShowStringFunc show_string;
   GetStringWidthFunc get_string_width;
 };
-  
- 
-extern PSUnicoder *ps_unicoder_new(const PSUnicoderCallbacks *psucbk, 
+
+
+extern PSUnicoder *ps_unicoder_new(const PSUnicoderCallbacks *psucbk,
                                    gpointer usrdata);
 extern void ps_unicoder_destroy(PSUnicoder *psu);
 
-extern void psu_set_font_face(PSUnicoder *psu, const gchar *face, float size);
+extern void psu_set_font_face(PSUnicoder *psu, const char *face, float size);
 /* just stores the font face and size we'll later use */
 
-extern void psu_check_string_encodings(PSUnicoder *psu, 
+extern void psu_check_string_encodings(PSUnicoder *psu,
                                        const char *utf8_string);
 /* appends what's going to be needed in the encoding tables */
 
@@ -131,7 +131,7 @@ extern void psu_get_string_width(PSUnicoder *psu,
 
 extern const char *unicode_to_ps_name(gunichar val);
 /* returns "uni1234", or a special Adobe entity name. */
- 
+
 
 #endif /* !PS_UTF8_H */
 
diff --git a/plug-ins/postscript/render_eps.c b/plug-ins/postscript/render_eps.c
index 01968004..b57a3bb3 100644
--- a/plug-ins/postscript/render_eps.c
+++ b/plug-ins/postscript/render_eps.c
@@ -63,42 +63,39 @@
 #include "font.h"
 #include "diapsrenderer.h"
 
-static gboolean export_eps        (DiagramData *data,
-                                   DiaContext  *ctx,
-                                   const gchar *filename,
-                                   const gchar *diafilename,
-                                   void        *user_data);
 
 static gboolean export_render_eps (DiaPsRenderer *renderer,
                                    DiagramData   *data,
                                    DiaContext    *ctx,
-                                   const gchar   *filename,
-                                   const gchar   *diafilename,
+                                   const char    *filename,
+                                   const char    *diafilename,
                                    void          *user_data);
 
+
 static gboolean
 export_eps (DiagramData *data,
             DiaContext  *ctx,
-            const gchar *filename,
-            const gchar *diafilename,
+            const char  *filename,
+            const char  *diafilename,
             void        *user_data)
 {
   gboolean ret;
   DiaPsRenderer *renderer = g_object_new (DIA_TYPE_PS_RENDERER, NULL);
 
   renderer->ctx = ctx;
-  ret = export_render_eps(renderer, data, ctx, filename, diafilename, user_data);
-  g_object_unref (renderer);
+  ret = export_render_eps (renderer, data, ctx, filename, diafilename, user_data);
+  g_clear_object (&renderer);
 
   return ret;
 }
 
+
 static gboolean
 export_render_eps (DiaPsRenderer *renderer,
                    DiagramData   *data,
                    DiaContext    *ctx,
-                   const gchar   *filename,
-                   const gchar   *diafilename,
+                   const char    *filename,
+                   const char    *diafilename,
                    void          *user_data)
 {
   FILE *outfile;
diff --git a/plug-ins/pstricks/render_pstricks.c b/plug-ins/pstricks/render_pstricks.c
index d41bf08e..382fbc41 100644
--- a/plug-ins/pstricks/render_pstricks.c
+++ b/plug-ins/pstricks/render_pstricks.c
@@ -835,42 +835,44 @@ draw_string (DiaRenderer *self,
             pstricks_dtostr (px_buf,pos->x),
             pstricks_dtostr (py_buf,pos->y),
             escaped ? escaped : text);
-  g_free (escaped);
+  g_clear_pointer (&escaped, g_free);
 }
 
 
 static void
-draw_image(DiaRenderer *self,
-          Point *point,
-          real width, real height,
-          DiaImage *image)
+draw_image (DiaRenderer *self,
+            Point       *point,
+            double       width,
+            double       height,
+            DiaImage    *image)
 {
-    PstricksRenderer *renderer = PSTRICKS_RENDERER(self);
-    int img_width, img_height;
-    int v;
-    int                 x, y;
-    unsigned char      *ptr;
-    guint8 *rgb_data;
-    gdouble points_in_inch = POINTS_in_INCH;
-    gchar points_in_inch_buf[DTOSTR_BUF_SIZE];
-    gchar px_buf[DTOSTR_BUF_SIZE];
-    gchar py_buf[DTOSTR_BUF_SIZE];
-    gchar width_buf[DTOSTR_BUF_SIZE];
-    gchar height_buf[DTOSTR_BUF_SIZE];
-
-    pstricks_dtostr(points_in_inch_buf,points_in_inch);
-
-    img_width = dia_image_width(image);
-    img_height = dia_image_height(image);
+  PstricksRenderer *renderer = PSTRICKS_RENDERER (self);
+  int img_width, img_height;
+  int v;
+  int                 x, y;
+  unsigned char      *ptr;
+  guint8 *rgb_data;
+  double points_in_inch = POINTS_in_INCH;
+  char points_in_inch_buf[DTOSTR_BUF_SIZE];
+  char px_buf[DTOSTR_BUF_SIZE];
+  char py_buf[DTOSTR_BUF_SIZE];
+  char width_buf[DTOSTR_BUF_SIZE];
+  char height_buf[DTOSTR_BUF_SIZE];
+
+  pstricks_dtostr (points_in_inch_buf, points_in_inch);
+
+  img_width = dia_image_width(image);
+  img_height = dia_image_height(image);
+
+  rgb_data = dia_image_rgb_data(image);
+  if (!rgb_data) {
+    dia_context_add_message(renderer->ctx, _("Not enough memory for image drawing."));
+    return;
+  }
 
-    rgb_data = dia_image_rgb_data(image);
-    if (!rgb_data) {
-        dia_context_add_message(renderer->ctx, _("Not enough memory for image drawing."));
-        return;
-    }
+  fprintf (renderer->file, "\\pscustom{\\code{gsave\n");
 
-    fprintf(renderer->file, "\\pscustom{\\code{gsave\n");
-    if (1) { /* Color output */
+  if (1) { /* Color output */
        fprintf(renderer->file, "/pix %i string def\n", img_width * 3);
        fprintf(renderer->file, "/grays %i string def\n", img_width);
        fprintf(renderer->file, "/npixls 0 def\n");
@@ -931,38 +933,43 @@ draw_image(DiaRenderer *self,
     fprintf(renderer->file, "grestore\n");
     fprintf(renderer->file, "}}\n");
 
-    g_free (rgb_data);
+  g_clear_pointer (&rgb_data, g_free);
 }
 
+
 /* --- export filter interface --- */
 static gboolean
-export_pstricks(DiagramData *data, DiaContext *ctx,
-               const gchar *filename, const gchar *diafilename,
-               void* user_data)
+export_pstricks (DiagramData *data,
+                 DiaContext  *ctx,
+                 const char  *filename,
+                 const char  *diafilename,
+                 void        *user_data)
 {
-    PstricksRenderer *renderer;
-    FILE *file;
-    time_t time_now;
-    DiaRectangle *extent;
-    const char *name;
-    gchar el_buf[DTOSTR_BUF_SIZE];
-    gchar er_buf[DTOSTR_BUF_SIZE];
-    gchar eb_buf[DTOSTR_BUF_SIZE];
-    gchar et_buf[DTOSTR_BUF_SIZE];
-    gchar scale1_buf[DTOSTR_BUF_SIZE];
-    gchar scale2_buf[DTOSTR_BUF_SIZE];
-
-    Color initial_color;
-
-    file = g_fopen(filename, "wb");
-
-    if (file == NULL) {
-       dia_context_add_message_with_errno (ctx, errno, _("Can't open output file %s"),
-                                           dia_context_get_filename(ctx));
-       return FALSE;
-    }
+  PstricksRenderer *renderer;
+  FILE *file;
+  time_t time_now;
+  DiaRectangle *extent;
+  const char *name;
+  char el_buf[DTOSTR_BUF_SIZE];
+  char er_buf[DTOSTR_BUF_SIZE];
+  char eb_buf[DTOSTR_BUF_SIZE];
+  char et_buf[DTOSTR_BUF_SIZE];
+  char scale1_buf[DTOSTR_BUF_SIZE];
+  char scale2_buf[DTOSTR_BUF_SIZE];
+
+  Color initial_color;
+
+  file = g_fopen(filename, "wb");
+
+  if (file == NULL) {
+    dia_context_add_message_with_errno (ctx,
+                                        errno,
+                                        _("Can't open output file %s"),
+                                        dia_context_get_filename (ctx));
+    return FALSE;
+  }
 
-    renderer = g_object_new(PSTRICKS_TYPE_RENDERER, NULL);
+  renderer = g_object_new (PSTRICKS_TYPE_RENDERER, NULL);
 
     renderer->pagenum = 1;
     renderer->file = file;
@@ -998,37 +1005,38 @@ export_pstricks(DiagramData *data, DiaContext *ctx,
        ctime(&time_now),
        name);
 
-    fprintf(renderer->file,"\\pspicture(%s,%s)(%s,%s)\n",
-           pstricks_dtostr(el_buf,extent->left * data->paper.scaling),
-           pstricks_dtostr(eb_buf,-extent->bottom * data->paper.scaling),
-           pstricks_dtostr(er_buf,extent->right * data->paper.scaling),
-           pstricks_dtostr(et_buf,-extent->top * data->paper.scaling) );
-    fprintf(renderer->file,"\\psscalebox{%s %s}{\n",
-           pstricks_dtostr(scale1_buf,data->paper.scaling),
-           pstricks_dtostr(scale2_buf,-data->paper.scaling) );
+  fprintf (renderer->file,"\\pspicture(%s,%s)(%s,%s)\n",
+           pstricks_dtostr (el_buf, extent->left * data->paper.scaling),
+           pstricks_dtostr (eb_buf, -extent->bottom * data->paper.scaling),
+           pstricks_dtostr (er_buf, extent->right * data->paper.scaling),
+           pstricks_dtostr (et_buf, -extent->top * data->paper.scaling) );
+  fprintf (renderer->file,"\\psscalebox{%s %s}{\n",
+           pstricks_dtostr (scale1_buf, data->paper.scaling),
+           pstricks_dtostr (scale2_buf, -data->paper.scaling) );
 
-    initial_color.red=0.;
-    initial_color.green=0.;
-    initial_color.blue=0.;
-    set_line_color(renderer,&initial_color);
+  initial_color.red = 0.0;
+  initial_color.green = 0.0;
+  initial_color.blue = 0.0;
+  set_line_color (renderer, &initial_color);
 
-    initial_color.red=1.;
-    initial_color.green=1.;
-    initial_color.blue=1.;
-    set_fill_color(renderer,&initial_color);
+  initial_color.red= 1.0;
+  initial_color.green= 1.0;
+  initial_color.blue= 1.0;
+  set_fill_color (renderer, &initial_color);
 
-    data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
+  data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
 
-    g_object_unref(renderer);
+  g_clear_object (&renderer);
 
-    return TRUE;
+  return TRUE;
 }
 
+
 static const gchar *extensions[] = { "tex", NULL };
 DiaExportFilter pstricks_export_filter = {
-    N_("TeX PSTricks macros"),
-    extensions,
-    export_pstricks,
-    NULL,
-    "pstricks-tex"
+  N_("TeX PSTricks macros"),
+  extensions,
+  export_pstricks,
+  NULL,
+  "pstricks-tex"
 };
diff --git a/plug-ins/python/diamodule.c b/plug-ins/python/diamodule.c
index ab1ee5ae..f42027a8 100644
--- a/plug-ins/python/diamodule.c
+++ b/plug-ins/python/diamodule.c
@@ -449,8 +449,8 @@ PyDia_RegisterCallback(PyObject *self, PyObject *args)
       *(strrchr (path, '/')) = '\0';
 #endif
     ret = _RegisterAction (action, desc, path, func);
-    g_free (path);
-    g_free (action);
+    g_clear_pointer (&path, g_free);
+    g_clear_pointer (&action, g_free);
 
     return ret;
 }
diff --git a/plug-ins/python/pydia-color.c b/plug-ins/python/pydia-color.c
index a554b142..7f101550 100644
--- a/plug-ins/python/pydia-color.c
+++ b/plug-ins/python/pydia-color.c
@@ -24,28 +24,32 @@
 
 #include <structmember.h> /* PyMemberDef */
 
+
 /*
  * New
  */
-PyObject* PyDiaColor_New (Color* color)
+PyObject *
+PyDiaColor_New (Color* color)
 {
   PyDiaColor *self;
-  
-  self = PyObject_NEW(PyDiaColor, &PyDiaColor_Type);
+
+  self = PyObject_NEW (PyDiaColor, &PyDiaColor_Type);
+
   if (!self) return NULL;
-  
+
   self->color = *color;
 
-  return (PyObject *)self;
+  return (PyObject *) self;
 }
 
+
 /*
  * Dealloc
  */
 static void
-PyDiaColor_Dealloc(PyObject *self)
+PyDiaColor_Dealloc (PyObject *self)
 {
-  PyObject_DEL(self);
+  PyObject_DEL (self);
 }
 
 /*
@@ -67,23 +71,25 @@ PyDiaColor_Hash(PyObject *self)
   return (long)self;
 }
 
+
 /*
  * Repr / _Str
  */
 static PyObject *
-PyDiaColor_Str(PyDiaColor *self)
+PyDiaColor_Str (PyDiaColor *self)
 {
   PyObject* py_s;
-  gchar* s = g_strdup_printf("(%f,%f,%f,%f)",
-                             (float)(self->color.red),
-                             (float)(self->color.green),
-                             (float)(self->color.blue),
-                             (float)(self->color.alpha));
-  py_s = PyString_FromString(s);
-  g_free (s);
+  gchar* s = g_strdup_printf ("(%f,%f,%f,%f)",
+                              (float) (self->color.red),
+                              (float) (self->color.green),
+                              (float) (self->color.blue),
+                              (float) (self->color.alpha));
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
   return py_s;
 }
 
+
 static PyMemberDef PyDiaColor_Members[] = {
     { "red", T_FLOAT, offsetof(PyDiaColor, color.red), 0,
       "double: red color component [0 .. 1.0]" },
diff --git a/plug-ins/python/pydia-diagram.c b/plug-ins/python/pydia-diagram.c
index 66d58f65..089dbdc4 100644
--- a/plug-ins/python/pydia-diagram.c
+++ b/plug-ins/python/pydia-diagram.c
@@ -36,26 +36,31 @@
 #include "app/load_save.h"
 #include "app/connectionpoint_ops.h"
 
+
 PyObject *
-PyDiaDiagram_New(Diagram *dia)
+PyDiaDiagram_New (Diagram *dia)
 {
-    PyDiaDiagram *self;
+  PyDiaDiagram *self;
+
+  self = PyObject_NEW (PyDiaDiagram, &PyDiaDiagram_Type);
+
+  if (!self) return NULL;
 
-    self = PyObject_NEW(PyDiaDiagram, &PyDiaDiagram_Type);
+  g_set_object (&self->dia, dia);
 
-    if (!self) return NULL;
-    g_object_ref(dia);
-    self->dia = dia;
-    return (PyObject *)self;
+  return (PyObject *) self;
 }
 
+
 static void
-PyDiaDiagram_Dealloc(PyDiaDiagram *self)
+PyDiaDiagram_Dealloc (PyDiaDiagram *self)
 {
-    g_object_unref(self->dia);
-    PyObject_DEL(self);
+  g_clear_object (&self->dia);
+
+  PyObject_DEL (self);
 }
 
+
 static int
 PyDiaDiagram_Compare(PyDiaDiagram *self, PyDiaDiagram *other)
 {
diff --git a/plug-ins/python/pydia-diagramdata.c b/plug-ins/python/pydia-diagramdata.c
index 90915c37..9416dde3 100644
--- a/plug-ins/python/pydia-diagramdata.c
+++ b/plug-ins/python/pydia-diagramdata.c
@@ -35,26 +35,31 @@
 #include "dia-layer.h"
 #include "pydia-diagram.h" /* support dynamic_cast */
 
+
 PyObject *
-PyDiaDiagramData_New(DiagramData *dd)
+PyDiaDiagramData_New (DiagramData *dd)
 {
-    PyDiaDiagramData *self;
+  PyDiaDiagramData *self;
+
+  self = PyObject_NEW (PyDiaDiagramData, &PyDiaDiagramData_Type);
 
-    self = PyObject_NEW(PyDiaDiagramData, &PyDiaDiagramData_Type);
+  if (!self) return NULL;
 
-    if (!self) return NULL;
-    g_object_ref (dd);
-    self->data = dd;
-    return (PyObject *)self;
+  g_set_object (&self->data, dd);
+
+  return (PyObject *) self;
 }
 
+
 static void
-PyDiaDiagramData_Dealloc(PyDiaDiagramData *self)
+PyDiaDiagramData_Dealloc (PyDiaDiagramData *self)
 {
-    g_object_unref (self->data);
-    PyObject_DEL(self);
+  g_clear_object (&self->data);
+
+  PyObject_DEL(self);
 }
 
+
 static int
 PyDiaDiagramData_Compare(PyDiaDiagramData *self, PyDiaDiagramData *other)
 {
@@ -69,16 +74,18 @@ PyDiaDiagramData_Hash(PyDiaDiagramData *self)
     return (long)self->data;
 }
 
+
 static PyObject *
 PyDiaDiagramData_Str(PyDiaDiagramData *self)
 {
-    PyObject* py_s;
-    gchar* s = g_strdup_printf ("<PyDiaDiagramData %p>", self);
-    py_s = PyString_FromString(s);
-    g_free(s);
-    return py_s;
+  PyObject* py_s;
+  char* s = g_strdup_printf ("<PyDiaDiagramData %p>", self);
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
+  return py_s;
 }
 
+
 /*
  * "real" member function implementaion ?
  */
@@ -112,10 +119,11 @@ PyDiaDiagramData_GetSortedSelected(PyDiaDiagramData *self, PyObject *args)
     return ret;
 }
 
+
 static PyObject *
 PyDiaDiagramData_AddLayer (PyDiaDiagramData *self, PyObject *args)
 {
-  gchar *name;
+  char *name;
   int pos = -1;
   DiaLayer *layer;
 
@@ -343,8 +351,9 @@ static PyMemberDef PyDiaDiagramData_Members[] = {
     { NULL }
 };
 
+
 static PyObject *
-PyDiaDiagramData_GetAttr(PyDiaDiagramData *self, gchar *attr)
+PyDiaDiagramData_GetAttr (PyDiaDiagramData *self, char *attr)
 {
     DiagramData *data = self->data;
 
@@ -384,19 +393,21 @@ PyDiaDiagramData_GetAttr(PyDiaDiagramData *self, gchar *attr)
     } else if (!strcmp(attr, "active_layer")) {
       return PyDiaLayer_New(data->active_layer);
     } else if (!strcmp(attr, "selected")) {
-       PyObject *ret;
-       GList *tmp;
-       gint i;
+      PyObject *ret;
+      GList *tmp;
+      int i;
 
-       ret = PyTuple_New(g_list_length(self->data->selected));
-       for (i = 0, tmp = data->selected; tmp; i++, tmp = tmp->next)
-           PyTuple_SetItem(ret, i, PyDiaObject_New((DiaObject *)tmp->data));
-       return ret;
+      ret = PyTuple_New (g_list_length (self->data->selected));
+      for (i = 0, tmp = data->selected; tmp; i++, tmp = tmp->next) {
+        PyTuple_SetItem (ret, i, PyDiaObject_New ((DiaObject *) tmp->data));
+      }
+      return ret;
     } else if (!strcmp(attr, "diagram")) {
-       if (DIA_IS_DIAGRAM (self->data))
-           return PyDiaDiagram_New (DIA_DIAGRAM (self->data));
-       Py_INCREF(Py_None);
-       return Py_None;
+      if (DIA_IS_DIAGRAM (self->data)) {
+        return PyDiaDiagram_New (DIA_DIAGRAM (self->data));
+      }
+      Py_INCREF (Py_None);
+      return Py_None;
     } else {
       /* In the interactive case diagramdata is_a diagram */
       if (DIA_IS_DIAGRAM (self->data)) {
diff --git a/plug-ins/python/pydia-error.c b/plug-ins/python/pydia-error.c
index 118ddcd5..2386e97b 100644
--- a/plug-ins/python/pydia-error.c
+++ b/plug-ins/python/pydia-error.c
@@ -47,7 +47,7 @@ _pyerror_report_last (gboolean popup, const char* fn, const char* file, int line
   PyTraceBack_Print(tb, ef);
   if (((PyDiaError*)ef)->str && popup)
     message_error ("%s", ((PyDiaError*)ef)->str->str);
-  g_free (sLoc);
+  g_clear_pointer (&sLoc, g_free);
   Py_DECREF (ef);
   Py_XDECREF(exc);
   Py_XDECREF(v);
diff --git a/plug-ins/python/pydia-font.c b/plug-ins/python/pydia-font.c
index 23e5e08e..f0640490 100644
--- a/plug-ins/python/pydia-font.c
+++ b/plug-ins/python/pydia-font.c
@@ -107,23 +107,25 @@ PyDiaFont_GetAttr(PyDiaFont *self, gchar *attr)
   return NULL;
 }
 
+
 /*
  * Repr / _Str
  */
 static PyObject *
-PyDiaFont_Str(PyDiaFont *self)
+PyDiaFont_Str (PyDiaFont *self)
 {
   PyObject *ret;
-  gchar *s = self->font ? g_strdup_printf ("%s %s %s",
-       dia_font_get_family (self->font),
-       dia_font_get_weight_string (self->font),
-       dia_font_get_slant_string (self->font)) : g_strdup("<DiaFont NULL>");
+  char *s = self->font ? g_strdup_printf ("%s %s %s",
+                                          dia_font_get_family (self->font),
+                                          dia_font_get_weight_string (self->font),
+                                          dia_font_get_slant_string (self->font)) : g_strdup ("<DiaFont 
NULL>");
 
-  ret = PyString_FromString(s);
-  g_free (s);
+  ret = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
   return ret;
 }
 
+
 #define T_INVALID -1 /* can't allow direct access due to pyobject->cpoint indirection */
 static PyMemberDef PyDiaFont_Members[] = {
     { "family", T_INVALID, 0, RESTRICTED|READONLY,
diff --git a/plug-ins/python/pydia-geometry.c b/plug-ins/python/pydia-geometry.c
index be73444b..a314cde9 100644
--- a/plug-ins/python/pydia-geometry.c
+++ b/plug-ins/python/pydia-geometry.c
@@ -213,8 +213,9 @@ PyDiaGeometry_Hash(PyObject *self)
     return (long)self;
 }
 
+
 static PyObject *
-PyDiaRectangle_GetAttr(PyDiaRectangle *self, gchar *attr)
+PyDiaRectangle_GetAttr(PyDiaRectangle *self, char *attr)
 {
 #define I_OR_F(v) \
   (self->is_int ? \
@@ -237,8 +238,9 @@ PyDiaRectangle_GetAttr(PyDiaRectangle *self, gchar *attr)
 #undef I_O_F
 }
 
+
 static PyObject *
-PyDiaBezPoint_GetAttr(PyDiaBezPoint *self, gchar *attr)
+PyDiaBezPoint_GetAttr(PyDiaBezPoint *self, char *attr)
 {
   if (!strcmp(attr, "__members__"))
     return Py_BuildValue("[ssss]", "type", "p1", "p2", "p3");
@@ -265,209 +267,248 @@ PyDiaBezPoint_GetAttr(PyDiaBezPoint *self, gchar *attr)
  * Repr / _Str
  */
 static PyObject *
-PyDiaPoint_Str(PyDiaPoint *self)
+PyDiaPoint_Str (PyDiaPoint *self)
 {
-    PyObject* py_s;
+  PyObject *py_s;
+
 #ifndef _DEBUG /* gives crashes with nan */
-    gchar* s = g_strdup_printf ("(%f,%f)",
-                                (float)(self->pt.x), (float)(self->pt.y));
+  char *s = g_strdup_printf ("(%f,%f)",
+                             (float) (self->pt.x),
+                             (float) (self->pt.y));
 #else
-    gchar* s = g_strdup_printf ("(%e,%e)",
-                                (float)(self->pt.x), (float)(self->pt.y));
+  char *s = g_strdup_printf ("(%e,%e)",
+                             (float) (self->pt.x),
+                             (float) (self->pt.y));
 #endif
-    py_s = PyString_FromString(s);
-    g_free(s);
-    return py_s;
+
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
+  return py_s;
 }
 
+
 static PyObject *
-PyDiaRectangle_Str(PyDiaRectangle *self)
+PyDiaRectangle_Str (PyDiaRectangle *self)
 {
-    PyObject* py_s;
-    gchar* s;
-    if (self->is_int)
-      s = g_strdup_printf ("((%d,%d),(%d,%d))",
-                           (self->r.ri.left), (self->r.ri.top),
-                           (self->r.ri.right), (self->r.ri.bottom));
-    else
+  PyObject *py_s;
+  char *s;
+
+  if (self->is_int) {
+    s = g_strdup_printf ("((%d,%d),(%d,%d))",
+                         (self->r.ri.left),
+                         (self->r.ri.top),
+                         (self->r.ri.right),
+                         (self->r.ri.bottom));
+  } else {
 #ifndef _DEBUG /* gives crashes with nan */
-      s = g_strdup_printf ("((%f,%f),(%f,%f))",
-                           (float)(self->r.rf.left), (float)(self->r.rf.top),
-                           (float)(self->r.rf.right), (float)(self->r.rf.bottom));
+    s = g_strdup_printf ("((%f,%f),(%f,%f))",
+                         (float) (self->r.rf.left),
+                         (float) (self->r.rf.top),
+                         (float) (self->r.rf.right),
+                         (float) (self->r.rf.bottom));
 #else
-      s = g_strdup_printf ("((%e,%e),(%e,%e))",
-                           (float)(self->r.rf.left), (float)(self->r.rf.top),
-                           (float)(self->r.rf.right), (float)(self->r.rf.bottom));
+    s = g_strdup_printf ("((%e,%e),(%e,%e))",
+                         (float) (self->r.rf.left),
+                         (float) (self->r.rf.top),
+                         (float) (self->r.rf.right),
+                         (float) (self->r.rf.bottom));
 #endif
-    py_s = PyString_FromString(s);
-    g_free(s);
-    return py_s;
+  }
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
+  return py_s;
 }
 
+
 static PyObject *
 PyDiaBezPoint_Str(PyDiaBezPoint *self)
 {
-    PyObject* py_s;
+  PyObject *py_s;
 #if 0 /* FIXME: this is causing bad crashes with unintialized points.
        * Probably a glib and a Dia problem ... */
-    gchar* s = g_strdup_printf ("((%f,%f),(%f,%f),(%f,%f),%s)",
-                                (float)(self->bpn.p1.x), (float)(self->bpn.p1.y),
-                                (float)(self->bpn.p2.x), (float)(self->bpn.p2.y),
-                                (float)(self->bpn.p3.x), (float)(self->bpn.p3.y),
-                                (self->bpn.type == BEZ_MOVE_TO ? "MOVE_TO" :
-                                  (self->bpn.type == BEZ_LINE_TO ? "LINE_TO" : "CURVE_TO")));
+  char* s = g_strdup_printf ("((%f,%f),(%f,%f),(%f,%f),%s)",
+                             (float)(self->bpn.p1.x), (float)(self->bpn.p1.y),
+                             (float)(self->bpn.p2.x), (float)(self->bpn.p2.y),
+                             (float)(self->bpn.p3.x), (float)(self->bpn.p3.y),
+                             (self->bpn.type == BEZ_MOVE_TO ? "MOVE_TO" :
+                             (self->bpn.type == BEZ_LINE_TO ? "LINE_TO" : "CURVE_TO")));
 #else
-    gchar* s = g_strdup_printf ("%s",
-                                (self->bpn.type == BEZ_MOVE_TO ? "MOVE_TO" :
-                                  (self->bpn.type == BEZ_LINE_TO ? "LINE_TO" : "CURVE_TO")));
+  char* s = g_strdup_printf ("%s",
+                             (self->bpn.type == BEZ_MOVE_TO ? "MOVE_TO" :
+                             (self->bpn.type == BEZ_LINE_TO ? "LINE_TO" : "CURVE_TO")));
 #endif
-    py_s = PyString_FromString(s);
-    g_free(s);
-    return py_s;
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
+  return py_s;
 }
 
 
 static PyObject *
 PyDiaArrow_Str(PyDiaArrow *self)
 {
-    PyObject* py_s;
-    gchar* s = g_strdup_printf ("(%f,%f, %d)",
-                                (float)(self->arrow.width),
-                                (float)(self->arrow.length),
-                                (int)(self->arrow.type));
-    py_s = PyString_FromString(s);
-    g_free(s);
-    return py_s;
+  PyObject* py_s;
+  char* s = g_strdup_printf ("(%f,%f, %d)",
+                             (float) (self->arrow.width),
+                             (float) (self->arrow.length),
+                             (int) (self->arrow.type));
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
+  return py_s;
 }
 
+
 static PyObject *
 PyDiaMatrix_Str(PyDiaMatrix *self)
 {
-    PyObject* py_s;
-    gchar* s = g_strdup_printf ("(%f, %f, %f, %f, %f, %f)",
-                                (float)(self->matrix.xx),
-                                (float)(self->matrix.yx),
-                                (float)(self->matrix.xy),
-                                (float)(self->matrix.yy),
-                                (float)(self->matrix.x0),
-                                (float)(self->matrix.y0));
-    py_s = PyString_FromString(s);
-    g_free(s);
-    return py_s;
+  PyObject *py_s;
+  char *s = g_strdup_printf ("(%f, %f, %f, %f, %f, %f)",
+                             (float) (self->matrix.xx),
+                             (float) (self->matrix.yx),
+                             (float) (self->matrix.xy),
+                             (float) (self->matrix.yy),
+                             (float) (self->matrix.x0),
+                             (float) (self->matrix.y0));
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
+  return py_s;
 }
 
+
 /*
  * sequence interface (query only)
  */
 /* Point */
 static gssize
-point_length(PyObject *self)
+point_length (PyObject *self)
 {
   return 2;
 }
+
+
 static PyObject *
-point_item(PyObject* o, gssize i)
+point_item (PyObject* o, gssize i)
 {
   PyDiaPoint* self = (PyDiaPoint*)o;
 
   switch (i) {
-  case 0 : return PyFloat_FromDouble(self->pt.x);
-  case 1 : return PyFloat_FromDouble(self->pt.y);
-  default :
-    PyErr_SetString(PyExc_IndexError, "PyDiaPoint index out of range");
-    return NULL;
+    case 0:
+      return PyFloat_FromDouble (self->pt.x);
+    case 1:
+      return PyFloat_FromDouble (self->pt.y);
+    default :
+      PyErr_SetString (PyExc_IndexError, "PyDiaPoint index out of range");
+      return NULL;
   }
 }
+
+
 static PyObject *
-point_slice(PyObject *o, gssize i, gssize j)
+point_slice (PyObject *o, gssize i, gssize j)
 {
   PyObject *ret;
 
   /* j maybe negative */
-  if (j <= 0)
+  if (j <= 0) {
     j = 1 + j;
+  }
   /* j may be rather huge [:] ^= 0:0x7FFFFFFF */
-  if (j > 1)
+  if (j > 1) {
     j = 1;
-  ret = PyTuple_New(j - i + 1);
+  }
+  ret = PyTuple_New (j - i + 1);
   if (ret) {
-    gssize k;
-    for (k = i; k <= j && k < 2; k++)
-      PyTuple_SetItem(ret, k - i, point_item(o, k));
+    for (gssize k = i; k <= j && k < 2; k++) {
+      PyTuple_SetItem (ret, k - i, point_item (o, k));
+    }
   }
   return ret;
 }
 
+
 static PySequenceMethods point_as_sequence = {
-       point_length, /*sq_length*/
-       (binaryfunc)0, /*sq_concat*/
-       0, /*sq_repeat*/
-       point_item, /*sq_item*/
-       point_slice, /*sq_slice*/
-       0,              /*sq_ass_item*/
-       0,              /*sq_ass_slice*/
-       (objobjproc)0 /*sq_contains*/
+  point_length,   /*sq_length*/
+  (binaryfunc) 0, /*sq_concat*/
+  0,              /*sq_repeat*/
+  point_item,     /*sq_item*/
+  point_slice,    /*sq_slice*/
+  0,              /*sq_ass_item*/
+  0,              /*sq_ass_slice*/
+  (objobjproc) 0  /*sq_contains*/
 };
 
+
 /* Rect */
 static gssize
-rect_length(PyObject *o)
+rect_length (PyObject *o)
 {
   return 4;
 }
+
+
 static PyObject *
-rect_item(PyObject *o, gssize i)
+rect_item (PyObject *o, gssize i)
 {
-  PyDiaRectangle* self = (PyDiaRectangle *)o;
+  PyDiaRectangle *self = (PyDiaRectangle *) o;
 
   switch (i) {
-  case 0 : return PyDiaRectangle_GetAttr(self, "left");
-  case 1 : return PyDiaRectangle_GetAttr(self, "top");
-  case 2 : return PyDiaRectangle_GetAttr(self, "right");
-  case 3 : return PyDiaRectangle_GetAttr(self, "bottom");
-  default :
-    PyErr_SetString(PyExc_IndexError, "PyDiaRectangle index out of range");
-    return NULL;
+    case 0:
+      return PyDiaRectangle_GetAttr (self, "left");
+    case 1:
+      return PyDiaRectangle_GetAttr (self, "top");
+    case 2:
+      return PyDiaRectangle_GetAttr (self, "right");
+    case 3:
+      return PyDiaRectangle_GetAttr (self, "bottom");
+    default :
+      PyErr_SetString (PyExc_IndexError, "PyDiaRectangle index out of range");
+      return NULL;
   }
 }
+
+
 static PyObject *
-rect_slice(PyObject* o, gssize i, gssize j)
+rect_slice (PyObject* o, gssize i, gssize j)
 {
   PyObject *ret;
 
   /* j maybe negative */
-  if (j <= 0)
+  if (j <= 0) {
     j = 3 + j;
+  }
   /* j may be rather huge [:] ^= 0:0x7FFFFFFF */
-  if (j > 3)
+  if (j > 3) {
     j = 3;
-  ret = PyTuple_New(j - i + 1);
+  }
+  ret = PyTuple_New (j - i + 1);
   if (ret) {
-    int k;
-    for (k = i; k <= j && k < 4; k++)
-      PyTuple_SetItem(ret, k - i, rect_item(o, k));
+    for (int k = i; k <= j && k < 4; k++) {
+      PyTuple_SetItem (ret, k - i, rect_item (o, k));
+    }
   }
   return ret;
 }
 
 static PySequenceMethods rect_as_sequence = {
-       rect_length, /*sq_length*/
-       (binaryfunc)0, /*sq_concat*/
-       0, /*sq_repeat*/
-       rect_item, /*sq_item*/
-       rect_slice, /*sq_slice*/
-       0,              /*sq_ass_item*/
-       0,              /*sq_ass_slice*/
-       (objobjproc)0 /*sq_contains*/
+  rect_length,    /*sq_length*/
+  (binaryfunc) 0, /*sq_concat*/
+  0,              /*sq_repeat*/
+  rect_item,      /*sq_item*/
+  rect_slice,     /*sq_slice*/
+  0,              /*sq_ass_item*/
+  0,              /*sq_ass_slice*/
+  (objobjproc) 0  /*sq_contains*/
 };
 
+
 static PyMemberDef PyDiaPoint_Members[] = {
-    { "x", T_DOUBLE, offsetof(PyDiaPoint, pt.x), 0,
-      "double: coordinate horizontal part" },
-    { "y", T_DOUBLE, offsetof(PyDiaPoint, pt.y), 0,
-      "double: coordinate vertical part" },
-    { NULL }
+  { "x", T_DOUBLE, offsetof (PyDiaPoint, pt.x), 0,
+    "double: coordinate horizontal part" },
+  { "y", T_DOUBLE, offsetof (PyDiaPoint, pt.y), 0,
+    "double: coordinate vertical part" },
+  { NULL }
 };
+
+
 /*
  * Python objetcs
  */
diff --git a/plug-ins/python/pydia-image.c b/plug-ins/python/pydia-image.c
index 2c2c3fb3..6541ff39 100644
--- a/plug-ins/python/pydia-image.c
+++ b/plug-ins/python/pydia-image.c
@@ -25,30 +25,34 @@
 
 #include <structmember.h> /* PyMemberDef */
 
+
 /*
  * New
  */
-PyObject* PyDiaImage_New (DiaImage *image)
+PyObject *
+PyDiaImage_New (DiaImage *image)
 {
   PyDiaImage *self;
-  
-  self = PyObject_NEW(PyDiaImage, &PyDiaImage_Type);
+
+  self = PyObject_NEW (PyDiaImage, &PyDiaImage_Type);
+
   if (!self) return NULL;
-  
-  dia_image_add_ref (image);
-  self->image = image;
 
-  return (PyObject *)self;
+  self->image = g_object_ref (image);
+
+  return (PyObject *) self;
 }
 
+
 /*
  * Dealloc
  */
 static void
-PyDiaImage_Dealloc(PyDiaImage *self)
+PyDiaImage_Dealloc (PyDiaImage *self)
 {
-  dia_image_unref (self->image);
-  PyObject_DEL(self);
+  g_clear_object (&self->image);
+
+  PyObject_DEL (self);
 }
 
 /*
@@ -70,93 +74,100 @@ PyDiaImage_Hash(PyObject *self)
   return (long)self;
 }
 
+
 /*
  * GetAttr
  */
 static PyObject *
-PyDiaImage_GetAttr(PyDiaImage *self, gchar *attr)
+PyDiaImage_GetAttr(PyDiaImage *self, char *attr)
 {
-  if (!strcmp(attr, "__members__"))
-    return Py_BuildValue("[ssssss]", "width", "height", 
+  if (!strcmp(attr, "__members__")) {
+    return Py_BuildValue("[ssssss]", "width", "height",
                                     "rgb_data", "mask_data",
                                     "filename", "uri");
-  else if (!strcmp(attr, "width"))
+  } else if (!strcmp(attr, "width"))
     return PyInt_FromLong(dia_image_width(self->image));
   else if (!strcmp(attr, "height"))
     return PyInt_FromLong(dia_image_height(self->image));
   else if (!strcmp(attr, "filename")) {
     return PyString_FromString(dia_image_filename(self->image));
-  }
-  else if (!strcmp(attr, "uri")) {
-    GError* error = NULL;
-    const gchar *fname = dia_image_filename(self->image);
+  } else if (!strcmp (attr, "uri")) {
+    GError *error = NULL;
+    const char *fname = dia_image_filename(self->image);
     char* s;
-    if (g_path_is_absolute(fname)) {
-      s = g_filename_to_uri(fname, NULL, &error);
+
+    if (g_path_is_absolute (fname)) {
+      s = g_filename_to_uri (fname, NULL, &error);
     } else {
-      gchar *prefix = g_strdup_printf ("data:%s;base64,", dia_image_get_mime_type (self->image));
+      char *prefix = g_strdup_printf ("data:%s;base64,",
+                                      dia_image_get_mime_type (self->image));
 
       s = pixbuf_encode_base64 (dia_image_pixbuf (self->image), prefix);
-      g_free (prefix);
+
+      g_clear_pointer (&prefix, g_free);
     }
+
     if (s) {
-      PyObject* py_s = PyString_FromString(s);
-      g_free(s);
+      PyObject* py_s = PyString_FromString (s);
+      g_clear_pointer (&s, g_free);
       return py_s;
     } else {
       if (error) {
-       PyErr_SetString(PyExc_RuntimeError, error->message);
-       g_error_free (error);
+        PyErr_SetString (PyExc_RuntimeError, error->message);
+        g_clear_error (&error);
       } else {
-       PyErr_SetString(PyExc_RuntimeError, "Pixbuf conversion failed?");
+        PyErr_SetString (PyExc_RuntimeError, "Pixbuf conversion failed?");
       }
       return NULL;
     }
-  }
-  else if (!strcmp(attr, "rgb_data")) {
-    unsigned char* s = dia_image_rgb_data(self->image);
-    int len = dia_image_width(self->image) * dia_image_height(self->image) * 3;
-    PyObject* py_s;
+  } else if (!strcmp (attr, "rgb_data")) {
+    unsigned char *s = dia_image_rgb_data (self->image);
+    int len = dia_image_width (self->image) * dia_image_height (self->image) * 3;
+    PyObject *py_s;
 
-    if (!s)
+    if (!s) {
       return PyErr_NoMemory();
-    py_s = PyString_FromStringAndSize((const char *)s, len);
-    g_free (s);
+    }
+
+    py_s = PyString_FromStringAndSize ((const char *) s, len);
+    g_clear_pointer (&s, g_free);
     return py_s;
-  }
-  else if (!strcmp(attr, "mask_data")) {
-    unsigned char* s = dia_image_mask_data(self->image);
-    int len = dia_image_width(self->image) * dia_image_height(self->image);
-    PyObject* py_s;
+  } else if (!strcmp (attr, "mask_data")) {
+    unsigned char *s = dia_image_mask_data (self->image);
+    int len = dia_image_width (self->image) * dia_image_height (self->image);
+    PyObject *py_s;
 
-    if (!s)
+    if (!s) {
       return PyErr_NoMemory();
-    py_s = PyString_FromStringAndSize((const char *)s, len);
-    g_free (s);
+    }
+    py_s = PyString_FromStringAndSize ((const char *) s, len);
+    g_clear_pointer (&s, g_free);
     return py_s;
   }
 
-  PyErr_SetString(PyExc_AttributeError, attr);
+  PyErr_SetString (PyExc_AttributeError, attr);
   return NULL;
 }
 
+
 /*
  * Repr / _Str
  */
 static PyObject *
-PyDiaImage_Str(PyDiaImage *self)
+PyDiaImage_Str (PyDiaImage *self)
 {
   PyObject* py_s;
-  const gchar* name = dia_image_filename(self->image);
-  gchar* s = g_strdup_printf("%ix%i,%s",
-                             dia_image_width(self->image),
-                             dia_image_height(self->image),
+  const char* name = dia_image_filename (self->image);
+  char* s = g_strdup_printf ("%ix%i,%s",
+                             dia_image_width (self->image),
+                             dia_image_height (self->image),
                              name ? name : "(null)");
-  py_s = PyString_FromString(s);
-  g_free (s);
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
   return py_s;
 }
 
+
 #define T_INVALID -1 /* can't allow direct access due to pyobject->cpoint indirection */
 static PyMemberDef PyDiaImage_Members[] = {
     { "width", T_INVALID, 0, RESTRICTED|READONLY,
diff --git a/plug-ins/python/pydia-layer.c b/plug-ins/python/pydia-layer.c
index ed43eb8f..76469202 100644
--- a/plug-ins/python/pydia-layer.c
+++ b/plug-ins/python/pydia-layer.c
@@ -225,7 +225,7 @@ PyDiaLayer_Render (PyDiaLayer *self, PyObject *args)
                     NULL, /* no special object renderer */
                     NULL, /* no user data */
                     active);
-  g_object_unref (wrapper);
+  g_clear_object (&wrapper);
 
   Py_INCREF (Py_None);
   return Py_None;
diff --git a/plug-ins/python/pydia-menuitem.c b/plug-ins/python/pydia-menuitem.c
index 7c275c12..22fbed89 100644
--- a/plug-ins/python/pydia-menuitem.c
+++ b/plug-ins/python/pydia-menuitem.c
@@ -24,21 +24,25 @@
 
 #include <structmember.h> /* PyMemberDef */
 
+
 /*
  * New
  */
-PyObject* PyDiaMenuitem_New (const DiaMenuItem *menuitem)
+PyObject *
+PyDiaMenuitem_New (const DiaMenuItem *menuitem)
 {
   PyDiaMenuitem *self;
-  
-  self = PyObject_NEW(PyDiaMenuitem, &PyDiaMenuitem_Type);
+
+  self = PyObject_NEW (PyDiaMenuitem, &PyDiaMenuitem_Type);
+
   if (!self) return NULL;
-  
+
   self->menuitem = menuitem;
 
   return (PyObject *)self;
 }
 
+
 /*
  * Dealloc
  */
@@ -97,7 +101,7 @@ PyDiaMenuitem_Call(PyDiaMenuitem *self, PyObject *args)
   if (!PyArg_ParseTuple(args, "O!(dd)|ii:Menuitem.callback",
                         &PyDiaObject_Type, &obj, &clicked.x, &clicked.y))
     return NULL;
-    
+
   mi = self->menuitem;
 
   oc = mi->callback (obj, &clicked, mi->callback_data);
@@ -105,7 +109,7 @@ PyDiaMenuitem_Call(PyDiaMenuitem *self, PyObject *args)
   if (oc) {
     if (oc->free)
       oc->free(oc);
-    g_free (oc);
+    g_clear_pointer (&oc, g_free);
   }
 
   Py_INCREF(Py_None);
@@ -118,13 +122,13 @@ static PyObject *
 PyDiaMenuitem_Str(PyDiaMenuitem *self)
 {
   PyObject* py_s;
-  gchar* s = g_strdup_printf("%s - %s,%s,%s",
-                             self->menuitem->text, 
-                            self->menuitem->active & DIAMENU_ACTIVE ? "active" : "inactive",
-                            self->menuitem->active & DIAMENU_TOGGLE ? "toggle" : "",
-                            self->menuitem->active & DIAMENU_TOGGLE_ON ? "on" : "");
-  py_s = PyString_FromString(s);
-  g_free (s);
+  gchar* s = g_strdup_printf ("%s - %s,%s,%s",
+                              self->menuitem->text,
+                              self->menuitem->active & DIAMENU_ACTIVE ? "active" : "inactive",
+                              self->menuitem->active & DIAMENU_TOGGLE ? "toggle" : "",
+                              self->menuitem->active & DIAMENU_TOGGLE_ON ? "on" : "");
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
   return py_s;
 }
 
diff --git a/plug-ins/python/pydia-object.c b/plug-ins/python/pydia-object.c
index da10e0dd..d08c9887 100644
--- a/plug-ins/python/pydia-object.c
+++ b/plug-ins/python/pydia-object.c
@@ -61,64 +61,71 @@ PyDiaObject_Hash(PyDiaObject *self)
     return (long)self->object;
 }
 
+
 static PyObject *
-PyDiaObject_Str(PyDiaObject *self)
+PyDiaObject_Str (PyDiaObject *self)
 {
-    gchar *strname = g_strdup_printf("<DiaObject of type \"%s\" at %lx>",
-                                    self->object->type->name,
-                                    (long)self->object);
-    PyObject *ret = PyString_FromString(strname);
+  char *strname = g_strdup_printf ("<DiaObject of type \"%s\" at %lx>",
+                                  self->object->type->name,
+                                  (long) self->object);
+  PyObject *ret = PyString_FromString (strname);
 
-    g_free(strname);
-    return ret;
+  g_clear_pointer (&strname, g_free);
+  return ret;
 }
 
+
 static PyObject *
 PyDiaObject_Destroy(PyDiaObject *self, PyObject *args)
 {
-    if (!PyArg_ParseTuple(args, ":Object.destroy"))
-       return NULL;
+  if (!PyArg_ParseTuple (args, ":Object.destroy")) {
+    return NULL;
+  }
 
-    if (!self->object->ops->destroy) {
-       PyErr_SetString(PyExc_RuntimeError,"object does not implement method");
-       return NULL;
-    }
+  if (!self->object->ops->destroy) {
+    PyErr_SetString(PyExc_RuntimeError,"object does not implement method");
+    return NULL;
+  }
 
-    self->object->ops->destroy(self->object);
-    g_free(self->object);
-    self->object = NULL;
-    Py_INCREF(Py_None);
-    return Py_None;
+  self->object->ops->destroy (self->object);
+  g_clear_pointer (&self->object, g_free);
+  Py_INCREF (Py_None);
+
+  return Py_None;
 }
 
+
 static PyObject *
-PyDiaObject_Draw(PyDiaObject *self, PyObject *args)
+PyDiaObject_Draw (PyDiaObject *self, PyObject *args)
 {
-    PyObject* renderer;
-    DiaRenderer *wrapper;
+  PyObject* renderer;
+  DiaRenderer *wrapper;
 
-    if (!PyArg_ParseTuple(args, "O:Object.draw", &renderer))
-       return NULL;
+  if (!PyArg_ParseTuple (args, "O:Object.draw", &renderer)) {
+    return NULL;
+  }
 
-    /* We need to create the PythonRenderer wrapper to provide the gobject interface.
-     * This could be done much more efficient if it would somehow be cached for the
-     * whole rendering pass ...
-     */
-    wrapper = PyDia_new_renderer_wrapper (renderer);
+  /* We need to create the PythonRenderer wrapper to provide the gobject interface.
+    * This could be done much more efficient if it would somehow be cached for the
+    * whole rendering pass ...
+    */
+  wrapper = PyDia_new_renderer_wrapper (renderer);
 
-    if (!self->object->ops->draw) {
-       PyErr_SetString(PyExc_RuntimeError,"object does not implement method");
-       return NULL;
-    }
+  if (!self->object->ops->draw) {
+    PyErr_SetString (PyExc_RuntimeError, "object does not implement method");
+    return NULL;
+  }
 
-    self->object->ops->draw(self->object, wrapper);
+  dia_object_draw (self->object, wrapper);
 
-    g_object_unref (wrapper);
+  g_clear_object (&wrapper);
 
-    Py_INCREF(Py_None);
-    return Py_None;
+  Py_INCREF (Py_None);
+
+  return Py_None;
 }
 
+
 static PyObject *
 PyDiaObject_DistanceFrom(PyDiaObject *self, PyObject *args)
 {
@@ -166,11 +173,11 @@ PyDiaObject_GetMenu(PyDiaObject *self, PyObject *args)
     Point clicked = { 0, 0 };
     DiaMenu *m;
     int i;
-    
+
 
     if (!PyArg_ParseTuple(args, ":Object.get_object_menu"))
        return NULL;
-       
+
     if (!self->object->ops->get_object_menu ||
         !(m = self->object->ops->get_object_menu (self->object, &clicked))) {
         Py_INCREF(Py_None);
@@ -279,8 +286,9 @@ static PyMemberDef PyDiaObject_Members[] = {
     { NULL }
 };
 
+
 static PyObject *
-PyDiaObject_GetAttr(PyDiaObject *self, gchar *attr)
+PyDiaObject_GetAttr (PyDiaObject *self, char *attr)
 {
     if (!strcmp(attr, "__members__"))
        return Py_BuildValue("[sssss]", "bounding_box", "connections",
@@ -384,63 +392,74 @@ PyDiaObjectType_Hash(PyDiaObjectType *self)
     return (long)self->otype;
 }
 
+
 static PyObject *
 PyDiaObjectType_Repr(PyDiaObjectType *self)
 {
-    gchar *strname = g_strdup_printf("<DiaObjectType \"%s\">",
-                                    self->otype->name);
-    PyObject *ret = PyString_FromString(strname);
+  char *strname = g_strdup_printf ("<DiaObjectType \"%s\">",
+                                   self->otype->name);
+  PyObject *ret = PyString_FromString (strname);
 
-    g_free(strname);
-    return ret;
+  g_clear_pointer (&strname, g_free);
+  return ret;
 }
 
+
 static PyObject *
 PyDiaObjectType_Str(PyDiaObjectType *self)
 {
     return PyString_FromString(self->otype->name);
 }
 
+
 static PyObject *
-PyDiaObjectType_Create(PyDiaObjectType *self, PyObject *args)
+PyDiaObjectType_Create (PyDiaObjectType *self, PyObject *args)
 {
-    Point p;
-    gint data = 0;
-    gpointer user_data;
-    DiaObject *ret;
-    Handle *h1 = NULL, *h2 = NULL;
-    PyObject *pyret;
-
-    if (!PyArg_ParseTuple(args, "dd|i:ObjectType.create", &p.x,&p.y, &data))
-       return NULL;
-    user_data = GINT_TO_POINTER(data);
-    if (!self->otype->ops) {
-       PyErr_SetString(PyExc_RuntimeError, "Type has no ops!?");
-       return NULL;
-    }
-    ret = self->otype->ops->create(&p, 
-                 user_data ? user_data : self->otype->default_user_data, &h1, &h2);
-    if (!ret) {
-       PyErr_SetString(PyExc_RuntimeError, "could not create new object");
-       return NULL;
-    }
-    pyret = PyTuple_New(3);
-    PyTuple_SetItem(pyret, 0, PyDiaObject_New(ret));
-    if (h1)
-       PyTuple_SetItem(pyret, 1, PyDiaHandle_New(h1, ret));
-    else {
-       Py_INCREF(Py_None);
-       PyTuple_SetItem(pyret, 1, Py_None);
-    }
-    if (h2)
-       PyTuple_SetItem(pyret, 2, PyDiaHandle_New(h2, ret));
-    else {
-       Py_INCREF(Py_None);
-       PyTuple_SetItem(pyret, 2, Py_None);
-    }
-    return pyret;
+  Point p;
+  gint data = 0;
+  gpointer user_data;
+  DiaObject *ret;
+  Handle *h1 = NULL, *h2 = NULL;
+  PyObject *pyret;
+
+  if (!PyArg_ParseTuple(args, "dd|i:ObjectType.create", &p.x,&p.y, &data)) {
+    return NULL;
+  }
+  user_data = GINT_TO_POINTER (data);
+  if (!self->otype->ops) {
+    PyErr_SetString (PyExc_RuntimeError, "Type has no ops!?");
+    return NULL;
+  }
+  ret = self->otype->ops->create (&p,
+                                  user_data ? user_data : self->otype->default_user_data,
+                                  &h1,
+                                  &h2);
+
+  if (!ret) {
+    PyErr_SetString (PyExc_RuntimeError, "could not create new object");
+    return NULL;
+  }
+
+  pyret = PyTuple_New (3);
+  PyTuple_SetItem (pyret, 0, PyDiaObject_New (ret));
+
+  if (h1) {
+    PyTuple_SetItem (pyret, 1, PyDiaHandle_New (h1, ret));
+  } else {
+    Py_INCREF (Py_None);
+    PyTuple_SetItem (pyret, 1, Py_None);
+  }
+
+  if (h2) {
+    PyTuple_SetItem (pyret, 2, PyDiaHandle_New (h2, ret));
+  } else {
+    Py_INCREF (Py_None);
+    PyTuple_SetItem (pyret, 2, Py_None);
+  }
+  return pyret;
 }
 
+
 static PyMethodDef PyDiaObjectType_Methods[] = {
     { "create", (PyCFunction)PyDiaObjectType_Create, METH_VARARGS,
       "create(real: x, real: y) -> (Object: o, Handle: h1, Handle: h2)"
@@ -456,19 +475,22 @@ static PyMemberDef PyDiaObjectType_Members[] = {
     { NULL }
 };
 
+
 static PyObject *
-PyDiaObjectType_GetAttr(PyDiaObjectType *self, gchar *attr)
+PyDiaObjectType_GetAttr (PyDiaObjectType *self, char *attr)
 {
-    if (!strcmp(attr, "__members__"))
-       return Py_BuildValue("[ss]", "name", "version");
-    else if (!strcmp(attr, "name"))
-       return PyString_FromString(self->otype->name);
-    else if (!strcmp(attr, "version"))
-       return PyInt_FromLong(self->otype->version);
-
-    return Py_FindMethod(PyDiaObjectType_Methods, (PyObject *)self, attr);
+  if (!strcmp (attr, "__members__")) {
+    return Py_BuildValue ("[ss]", "name", "version");
+  } else if (!strcmp (attr, "name")) {
+    return PyString_FromString (self->otype->name);
+  } else if (!strcmp (attr, "version")) {
+    return PyInt_FromLong (self->otype->version);
+  }
+
+  return Py_FindMethod (PyDiaObjectType_Methods, (PyObject *) self, attr);
 }
 
+
 PyTypeObject PyDiaObjectType_Type = {
     PyObject_HEAD_INIT(NULL)
     0,
diff --git a/plug-ins/python/pydia-paperinfo.c b/plug-ins/python/pydia-paperinfo.c
index 0fd41b40..cb47501f 100644
--- a/plug-ins/python/pydia-paperinfo.c
+++ b/plug-ins/python/pydia-paperinfo.c
@@ -24,21 +24,25 @@
 
 #include <structmember.h> /* PyMemberDef */
 
+
 /*
  * New
  */
-PyObject* PyDiaPaperinfo_New (const PaperInfo *paper)
+PyObject *
+PyDiaPaperinfo_New (const PaperInfo *paper)
 {
   PyDiaPaperinfo *self;
-  
-  self = PyObject_NEW(PyDiaPaperinfo, &PyDiaPaperinfo_Type);
+
+  self = PyObject_NEW (PyDiaPaperinfo, &PyDiaPaperinfo_Type);
+
   if (!self) return NULL;
-  
+
   self->paper = paper;
 
   return (PyObject *)self;
 }
 
+
 /*
  * Dealloc
  */
@@ -68,14 +72,15 @@ PyDiaPaperinfo_Hash(PyObject *self)
   return (long)self;
 }
 
+
 /*
  * GetAttr
  */
 static PyObject *
-PyDiaPaperinfo_GetAttr(PyDiaPaperinfo *self, gchar *attr)
+PyDiaPaperinfo_GetAttr(PyDiaPaperinfo *self, char *attr)
 {
   if (!strcmp(attr, "__members__"))
-    return Py_BuildValue("[sssss]", "name", "is_portrait", 
+    return Py_BuildValue("[sssss]", "name", "is_portrait",
                                     "scaling",
                                     "width", "height");
   else if (!strcmp(attr, "name"))
@@ -93,6 +98,7 @@ PyDiaPaperinfo_GetAttr(PyDiaPaperinfo *self, gchar *attr)
   return NULL;
 }
 
+
 /*
  * Repr / _Str
  */
@@ -100,15 +106,17 @@ static PyObject *
 PyDiaPaperinfo_Str(PyDiaPaperinfo *self)
 {
   PyObject* py_s;
-  gchar* s = g_strdup_printf("%s - %fx%f %f%%",
-                             self->paper->name ? self->paper->name : "(null)", 
-                            self->paper->width, self->paper->height,
-                            self->paper->scaling);
-  py_s = PyString_FromString(s);
-  g_free (s);
+  char* s = g_strdup_printf ("%s - %fx%f %f%%",
+                             self->paper->name ? self->paper->name : "(null)",
+                             self->paper->width,
+                             self->paper->height,
+                             self->paper->scaling);
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
   return py_s;
 }
 
+
 #define T_INVALID -1 /* can't allow direct access due to pyobject->paper indirection */
 static PyMemberDef PyDiaPaperinfo_Members[] = {
     { "name", T_INVALID, 0, RESTRICTED|READONLY,
diff --git a/plug-ins/python/pydia-properties.c b/plug-ins/python/pydia-properties.c
index 68c1b08f..c0bef0c3 100644
--- a/plug-ins/python/pydia-properties.c
+++ b/plug-ins/python/pydia-properties.c
@@ -77,10 +77,10 @@ static PyObject *
 PyDiaProperties_Str(PyDiaProperties *self)
 {
   PyObject* py_s;
-  gchar* s = g_strdup_printf("<DiaProperties at %p of DiaObject at %p>",
+  char* s = g_strdup_printf ("<DiaProperties at %p of DiaObject at %p>",
                              self, self->object );
-  py_s = PyString_FromString(s);
-  g_free (s);
+  py_s = PyString_FromString (s);
+  g_clear_pointer (&s, g_free);
   return py_s;
 }
 
@@ -274,7 +274,7 @@ static PyMemberDef PyDiaProperties_Members[] = {
  * GetAttr
  */
 static PyObject*
-PyDiaProperties_GetAttr(PyDiaProperties *self, gchar *attr)
+PyDiaProperties_GetAttr(PyDiaProperties *self, char *attr)
 {
   return Py_FindMethod(PyDiaProperties_Methods, (PyObject *)self, attr);
 }
diff --git a/plug-ins/python/pydia-property.c b/plug-ins/python/pydia-property.c
index 401d1ecb..1792aca3 100644
--- a/plug-ins/python/pydia-property.c
+++ b/plug-ins/python/pydia-property.c
@@ -303,12 +303,14 @@ PyDia_set_Matrix (Property *prop, PyObject *val)
   }
   return -1;
 }
+
+
 static int
 PyDia_set_Color (Property *prop, PyObject *val)
 {
   ColorProperty *p = (ColorProperty*)prop;
   if (PyString_Check(val)) {
-    gchar *str = PyString_AsString(val);
+    char *str = PyString_AsString(val);
     PangoColor color;
     if (pango_color_parse(&color, str)) {
       p->color_data.red = color.red / 65535.0;
@@ -400,69 +402,82 @@ PyDia_set_Fontsize(Property *prop, PyObject *val)
   return -1;
 }
 
+
 static int
-PyDia_set_String(Property *prop, PyObject *val)
+PyDia_set_String (Property *prop, PyObject *val)
 {
   StringProperty *p = (StringProperty *)prop;
+
   if (Py_None == val) {
     /* XXX: maybe a little dangerous, string = NULL not handle in everystring prop */
-    g_free (p->string_data);
-    p->string_data = NULL;
+    g_clear_pointer (&p->string_data, g_free);
     p->num_lines = 0;
     return 0;
   } else if (PyString_Check (val)) {
-    gchar *str = PyString_AsString (val);
-    g_free (p->string_data);
+    char *str = PyString_AsString (val);
+    g_clear_pointer (&p->string_data, g_free);
     p->string_data = g_strdup (str);
     p->num_lines = 1;
     return 0;
   } else if (PyUnicode_Check (val)) {
     PyObject *uval = PyUnicode_AsUTF8String (val);
-    gchar *str = PyString_AsString(uval);
-    g_free (p->string_data);
+    char *str = PyString_AsString(uval);
+    g_clear_pointer (&p->string_data, g_free);
     p->string_data = g_strdup (str);
     p->num_lines = 1;
     Py_DECREF (uval);
     return 0;
   }
+
   return -1;
 }
+
+
 static int
-PyDia_set_Text(Property *prop, PyObject *val)
+PyDia_set_Text (Property *prop, PyObject *val)
 {
   TextProperty *p = (TextProperty *)prop;
+
   if (PyString_Check (val)) {
-    gchar *str = PyString_AsString (val);
-    g_free (p->text_data);
+    char *str = PyString_AsString (val);
+    g_clear_pointer (&p->text_data, g_free);
     p->text_data = g_strdup (str);
     /* XXX: update size calculation ? */
     return 0;
   } else if (PyUnicode_Check (val)) {
     PyObject *uval = PyUnicode_AsUTF8String (val);
-    gchar *str = PyString_AsString(uval);
-    g_free (p->text_data);
+    char *str = PyString_AsString(uval);
+    g_clear_pointer (&p->text_data, g_free);
     p->text_data = g_strdup (str);
     Py_DECREF (uval);
     return 0;
   }
+
   return -1;
 }
+
+
 static int
-PyDia_set_Point(Property *prop, PyObject *val)
+PyDia_set_Point (Property *prop, PyObject *val)
 {
-  PointProperty *p = (PointProperty*)prop;
+  PointProperty *p = (PointProperty*) prop;
+
   if (PyTuple_Check(val) && PyTuple_Size(val) == 2) {
     p->point_data.x = PyFloat_AsDouble(PyTuple_GetItem(val, 0));
     p->point_data.y = PyFloat_AsDouble(PyTuple_GetItem(val, 1));
     return 0;
   }
+
   return -1;
 }
+
+
 static int
-PyDia_set_PointArray(Property *prop, PyObject *val)
+PyDia_set_PointArray (Property *prop, PyObject *val)
 {
   /* accept either tuple or list */
-  PointarrayProperty *ptp = (PointarrayProperty *)prop;
+  PointarrayProperty *ptp = (PointarrayProperty *) prop;
+
   if (PyTuple_Check(val) || PyList_Check(val)) {
     Point pt;
     gboolean is_list = !PyTuple_Check(val);
@@ -472,16 +487,16 @@ PyDia_set_PointArray(Property *prop, PyObject *val)
     for (i = 0; i < len; i++) {
       PyObject *o = is_list ? PyList_GetItem(val, i) : PyTuple_GetItem(val, i);
       if (PyTuple_Check(o)) {
-       pt.x = PyFloat_AsDouble(PyTuple_GetItem(o, 0));
-       pt.y = PyFloat_AsDouble(PyTuple_GetItem(o, 1));
-        g_array_index(ptp->pointarray_data,Point,i) = pt;
-       is_flat = FALSE;
+        pt.x = PyFloat_AsDouble (PyTuple_GetItem (o, 0));
+        pt.y = PyFloat_AsDouble (PyTuple_GetItem (o, 1));
+        g_array_index (ptp->pointarray_data, Point, i) = pt;
+        is_flat = FALSE;
       } else {
-       if (i % 2) {
-         pt.x = PyFloat_AsDouble(PyTuple_GetItem(val, i-1));
-         pt.y = PyFloat_AsDouble(PyTuple_GetItem(val, i));
-          g_array_index(ptp->pointarray_data,Point,i/2) = pt;
-       }
+        if (i % 2) {
+          pt.x = PyFloat_AsDouble(PyTuple_GetItem(val, i - 1));
+          pt.y = PyFloat_AsDouble(PyTuple_GetItem(val, i));
+          g_array_index (ptp->pointarray_data, Point, i / 2) = pt;
+        }
       }
     }
     if (is_flat)
@@ -648,7 +663,7 @@ PyDia_get_Array (ArrayProperty *prop)
       }
       PyTuple_SetItem(ret, i, o);
     }
-    g_free(getters);
+    g_clear_pointer (&getters, g_free);
   }
 
   return ret;
@@ -672,7 +687,7 @@ PyDia_set_Array (Property *prop, PyObject *val)
     }
     if (!setters[i]) {
       g_debug ("%s: No setter for '%s'", G_STRLOC, ex->descr->type);
-      g_free(setters);
+      g_clear_pointer (&setters, g_free);
       return -1;
     }
   }
@@ -728,35 +743,46 @@ PyDia_set_Array (Property *prop, PyObject *val)
         break;
     }
   }
-  g_free(setters);
+  g_clear_pointer (&setters, g_free);
   return ret;
 }
 
+
 static void
 _keyvalue_get (gpointer key,
                gpointer value,
                gpointer user_data)
 {
-  gchar *name = (gchar *)key;
-  gchar *val = (gchar *)value;
+  char *name = (char *) key;
+  char *val = (char *) value;
   PyObject *dict = (PyObject *)user_data;
   PyObject *k, *v;
 
-  k = PyString_FromString(name);
-  v = PyString_FromString(val);
-  if (k && v)
-    PyDict_SetItem(dict, k, v);
-  Py_XDECREF(k);
-  Py_XDECREF(v);
+  k = PyString_FromString (name);
+  v = PyString_FromString (val);
+
+  if (k && v) {
+    PyDict_SetItem (dict, k, v);
+  }
+
+  Py_XDECREF (k);
+  Py_XDECREF (v);
 }
+
+
 static PyObject *
 PyDia_get_Dict (DictProperty *prop)
 {
   PyObject *dict = PyDict_New();
-  if (prop->dict)
+
+  if (prop->dict) {
     g_hash_table_foreach (prop->dict, _keyvalue_get, dict);
+  }
+
   return dict;
 }
+
+
 static int
 PyDia_set_Dict (Property *prop, PyObject *val)
 {
@@ -767,8 +793,9 @@ PyDia_set_Dict (Property *prop, PyObject *val)
     PyObject *key, *value;
 
 
-    if (!p->dict)
+    if (!p->dict) {
       p->dict = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
+    }
 
     while (PyDict_Next(val, &i, &key, &value)) {
       /* CHECK semantics: replace or add? */
@@ -781,6 +808,7 @@ PyDia_set_Dict (Property *prop, PyObject *val)
   return -1;
 }
 
+
 static PyObject *
 PyDia_get_Pixbuf (PixbufProperty *prop)
 {
@@ -794,10 +822,12 @@ PyDia_get_Pixbuf (PixbufProperty *prop)
 
   return pb;
 }
+
+
 static int
 PyDia_set_Pixbuf (Property *prop, PyObject *val)
 {
-  PixbufProperty *p = (PixbufProperty *)prop;
+  PixbufProperty *p = (PixbufProperty *) prop;
 
   if PyCObject_Check(val) {
     gpointer pp = PyCObject_AsVoidPtr (val);
@@ -809,11 +839,12 @@ PyDia_set_Pixbuf (Property *prop, PyObject *val)
   return -1;
 }
 
+
 /*
  * GetAttr
  */
 static PyObject *
-PyDiaProperty_GetAttr(PyDiaProperty *self, gchar *attr)
+PyDiaProperty_GetAttr(PyDiaProperty *self, char *attr)
 {
 
   if (!strcmp(attr, "__members__"))
@@ -851,14 +882,15 @@ PyDiaProperty_GetAttr(PyDiaProperty *self, gchar *attr)
   return NULL;
 }
 
+
 /*
  * Similar to SetAttr but the property is directly applied
  * to the DiaObject
  */
-int PyDiaProperty_ApplyToObject (DiaObject   *object,
-                                 gchar    *key,
-                                 Property *prop,
-                                 PyObject *val)
+int PyDiaProperty_ApplyToObject (DiaObject *object,
+                                 char      *key,
+                                 Property  *prop,
+                                 PyObject  *val)
 {
   int ret = -1;
 
@@ -915,25 +947,27 @@ int PyDiaProperty_ApplyToObject (DiaObject   *object,
   return ret;
 }
 
+
 /*
  * Repr / _Str
  */
 static PyObject *
-PyDiaProperty_Str(PyDiaProperty *self)
+PyDiaProperty_Str (PyDiaProperty *self)
 {
   PyObject* py_s;
-  gchar* s;
+  char* s;
 
-  s = g_strdup_printf("<DiaProperty at %p, \"%s\", %s>",
-                      self,
-                      self->property->descr->name,
-                      self->property->descr->type);
+  s = g_strdup_printf ("<DiaProperty at %p, \"%s\", %s>",
+                       self,
+                       self->property->descr->name,
+                       self->property->descr->type);
 
   py_s = PyString_FromString(s);
-  g_free (s);
+  g_clear_pointer (&s, g_free);
   return py_s;
 }
 
+
 #define T_INVALID -1 /* can't allow direct access due to pyobject->property indirection */
 static PyMemberDef PyDiaProperty_Members[] = {
     { "name", T_INVALID, 0, RESTRICTED|READONLY,
diff --git a/plug-ins/python/pydia-render.c b/plug-ins/python/pydia-render.c
index 7dfa647f..abe09502 100644
--- a/plug-ins/python/pydia-render.c
+++ b/plug-ins/python/pydia-render.c
@@ -151,13 +151,13 @@ end_render(DiaRenderer *renderer)
     Py_DECREF(self);
   }
 
-  Py_DECREF (DIA_PY_RENDERER(renderer)->diagram_data);
-  g_free (DIA_PY_RENDERER(renderer)->filename);
-  DIA_PY_RENDERER(renderer)->filename = NULL;
+  Py_DECREF (DIA_PY_RENDERER (renderer)->diagram_data);
+  g_clear_pointer (&(DIA_PY_RENDERER (renderer)->filename), g_free);
 
-  setlocale(LC_NUMERIC, DIA_PY_RENDERER(renderer)->old_locale);
+  setlocale (LC_NUMERIC, DIA_PY_RENDERER (renderer)->old_locale);
 }
 
+
 /*!
  * \brief Set linewidth for later use
  *
@@ -496,6 +496,7 @@ draw_object (DiaRenderer *renderer, DiaObject *object, DiaMatrix *matrix)
   }
 }
 
+
 /*!
  * \brief Draw line
  *
@@ -505,41 +506,42 @@ draw_object (DiaRenderer *renderer, DiaObject *object, DiaMatrix *matrix)
  * \memberof _DiaPyRenderer
  */
 static void
-draw_line(DiaRenderer *renderer,
-          Point *start, Point *end,
-          Color *line_colour)
+draw_line (DiaRenderer *renderer,
+           Point       *start,
+           Point       *end,
+           Color       *line_colour)
 {
   PyObject *func, *res, *arg, *self = PYDIA_RENDERER (renderer);
 
   func = PyObject_GetAttrString (self, "draw_line");
-  if (func && PyCallable_Check(func)) {
+  if (func && PyCallable_Check (func)) {
     PyObject *ostart = PyDiaPoint_New (start);
     PyObject *oend = PyDiaPoint_New (end);
     PyObject *ocolor = PyDiaColor_New (line_colour);
 
-    Py_INCREF(self);
-    Py_INCREF(func);
+    Py_INCREF (self);
+    Py_INCREF (func);
     arg = Py_BuildValue ("(OOO)", ostart, oend, ocolor);
     if (arg) {
       res = PyEval_CallObject (func, arg);
-      ON_RES(res, FALSE);
+      ON_RES (res, FALSE);
     }
     Py_XDECREF (arg);
     Py_XDECREF (ostart);
     Py_XDECREF (oend);
     Py_XDECREF (ocolor);
-    Py_DECREF(func);
-    Py_DECREF(self);
-  }
-  else { /* member not optional */
-    gchar *msg = g_strdup_printf ("%s.draw_line() implementation missing.",
-                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
-    PyErr_Clear();
+    Py_DECREF (func);
+    Py_DECREF (self);
+  } else { /* member not optional */
+    char *msg = g_strdup_printf ("%s.draw_line() implementation missing.",
+                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
+    PyErr_Clear ();
     PyErr_Warn (PyExc_RuntimeWarning, msg);
-    g_free (msg);
+    g_clear_pointer (&msg, g_free);
   }
 }
 
+
 /*!
  * \brief Draw polyline
  *
@@ -738,13 +740,12 @@ draw_arc(DiaRenderer *renderer,
     Py_XDECREF (ocolor);
     Py_DECREF(func);
     Py_DECREF(self);
-  }
-  else { /* member not optional */
-    gchar *msg = g_strdup_printf ("%s.draw_arc() implementation missing.",
-                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
+  } else { /* member not optional */
+    char *msg = g_strdup_printf ("%s.draw_arc() implementation missing.",
+                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
     PyErr_Clear();
     PyErr_Warn (PyExc_RuntimeWarning, msg);
-    g_free (msg);
+    g_clear_pointer (&msg, g_free);
   }
 }
 
@@ -784,13 +785,12 @@ fill_arc(DiaRenderer *renderer,
     Py_XDECREF (ocolor);
     Py_DECREF(func);
     Py_DECREF(self);
-  }
-  else { /* member not optional */
-    gchar *msg = g_strdup_printf ("%s.fill_arc() implementation missing.",
-                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
-    PyErr_Clear();
+  } else { /* member not optional */
+    char *msg = g_strdup_printf ("%s.fill_arc() implementation missing.",
+                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
+    PyErr_Clear ();
     PyErr_Warn (PyExc_RuntimeWarning, msg);
-    g_free (msg);
+    g_clear_pointer (&msg, g_free);
   }
 }
 
@@ -839,11 +839,11 @@ draw_ellipse(DiaRenderer *renderer,
     Py_DECREF(func);
     Py_DECREF(self);
   } else { /* member not optional */
-    gchar *msg = g_strdup_printf ("%s.draw_ellipse() implementation missing.",
-                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
-    PyErr_Clear();
+    char *msg = g_strdup_printf ("%s.draw_ellipse() implementation missing.",
+                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
+    PyErr_Clear ();
     PyErr_Warn (PyExc_RuntimeWarning, msg);
-    g_free (msg);
+    g_clear_pointer (&msg, g_free);
   }
 }
 
@@ -1008,11 +1008,11 @@ draw_string(DiaRenderer *renderer,
     Py_DECREF(func);
     Py_DECREF(self);
   } else { /* member not optional */
-    gchar *msg = g_strdup_printf ("%s.draw_string() implementation missing.",
-                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
-    PyErr_Clear();
+    char *msg = g_strdup_printf ("%s.draw_string() implementation missing.",
+                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
+    PyErr_Clear ();
     PyErr_Warn (PyExc_RuntimeWarning, msg);
-    g_free (msg);
+    g_clear_pointer (&msg, g_free);
   }
 }
 
@@ -1050,17 +1050,21 @@ draw_image(DiaRenderer *renderer,
     Py_DECREF(func);
     Py_DECREF(self);
   } else { /* member not optional */
-    gchar *msg = g_strdup_printf ("%s.draw_image() implementation missing.",
-                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
-    PyErr_Clear();
+    char *msg = g_strdup_printf ("%s.draw_image() implementation missing.",
+                                 G_OBJECT_CLASS_NAME (G_OBJECT_GET_CLASS (renderer)));
+    PyErr_Clear ();
     PyErr_Warn (PyExc_RuntimeWarning, msg);
-    g_free (msg);
+    g_clear_pointer (&msg, g_free);
   }
 }
 
+
 gboolean
-PyDia_export_data(DiagramData *data, DiaContext *ctx,
-                 const gchar *filename, const gchar *diafilename, void* user_data)
+PyDia_export_data (DiagramData *data,
+                   DiaContext  *ctx,
+                   const char  *filename,
+                   const char  *diafilename,
+                   void        *user_data)
 {
   DiaPyRenderer *renderer;
 
@@ -1080,19 +1084,20 @@ PyDia_export_data(DiagramData *data, DiaContext *ctx,
   renderer = g_object_new (DIA_TYPE_PY_RENDERER, NULL);
 
   renderer->filename = g_strdup (filename);
-  renderer->diagram_data = PyDiaDiagramData_New(data);
+  renderer->diagram_data = PyDiaDiagramData_New (data);
 
   /* The Python Renderer object was created at PyDia_Register */
-  renderer->self = (PyObject*)user_data;
+  renderer->self = (PyObject*) user_data;
 
   /* this will call the required callback functions above */
-  data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
+  data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
 
-  g_object_unref(renderer);
+  g_clear_object (&renderer);
 
   return TRUE;
 }
 
+
 DiaRenderer *
 PyDia_new_renderer_wrapper (PyObject *self)
 {
@@ -1142,8 +1147,7 @@ dia_py_renderer_finalize (GObject *object)
 {
   DiaPyRenderer *renderer = DIA_PY_RENDERER (object);
 
-  if (renderer->filename)
-    g_free (renderer->filename);
+  g_clear_pointer (&renderer->filename, g_free);
 
   G_OBJECT_CLASS (parent_class)->finalize (object);
 }
diff --git a/plug-ins/python/pydia-text.c b/plug-ins/python/pydia-text.c
index 7a1f2b63..56d1fe7d 100644
--- a/plug-ins/python/pydia-text.c
+++ b/plug-ins/python/pydia-text.c
@@ -28,29 +28,33 @@
 
 #include <structmember.h> /* PyMemberDef */
 
+
 /*
  * New
  */
-PyObject* PyDiaText_New (gchar *text_data, TextAttributes *attr)
+PyObject *
+PyDiaText_New (char *text_data, TextAttributes *attr)
 {
   PyDiaText *self;
-  
-  self = PyObject_NEW(PyDiaText, &PyDiaText_Type);
+
+  self = PyObject_NEW (PyDiaText, &PyDiaText_Type);
+
   if (!self) return NULL;
-  
+
   self->text_data = g_strdup (text_data);
   self->attr = *attr;
 
   return (PyObject *)self;
 }
 
+
 /*
  * Dealloc
  */
 static void
 PyDiaText_Dealloc(PyDiaText *self)
 {
-  g_free (self->text_data);
+  g_clear_pointer (&self->text_data, g_free);
   PyObject_DEL(self);
 }
 
@@ -81,10 +85,10 @@ PyDiaText_Hash(PyObject *self)
  * GetAttr
  */
 static PyObject *
-PyDiaText_GetAttr(PyDiaText *self, gchar *attr)
+PyDiaText_GetAttr(PyDiaText *self, char *attr)
 {
   if (!strcmp(attr, "__members__"))
-    return Py_BuildValue("[sssss]", "text", "font", "height", 
+    return Py_BuildValue("[sssss]", "text", "font", "height",
                          "position", "color", "alignment");
   else if (!strcmp(attr, "text"))
     return PyString_FromString(self->text_data);
@@ -109,12 +113,12 @@ PyDiaText_GetAttr(PyDiaText *self, gchar *attr)
 static PyObject *
 PyDiaText_Str(PyDiaText *self)
 {
-  gchar *strname = g_strdup_printf("<DiaText \"%s\" at %lx>",
+  char *strname = g_strdup_printf ("<DiaText \"%s\" at %lx>",
                                    self->attr.font ? dia_font_get_family (self->attr.font) : "none",
                                    (long)self);
   PyObject *ret = PyString_FromString(strname);
 
-  g_free(strname);
+  g_clear_pointer (&strname, g_free);
   return ret;
 }
 
diff --git a/plug-ins/python/python.c b/plug-ins/python/python.c
index 7093cca5..2b066624 100644
--- a/plug-ins/python/python.c
+++ b/plug-ins/python/python.c
@@ -77,96 +77,109 @@ dia_py_plugin_unload (PluginInfo *info)
     Py_Finalize ();
 }
 
+
 PluginInitResult
-dia_plugin_init(PluginInfo *info)
+dia_plugin_init (PluginInfo *info)
 {
-    gchar *python_argv[] = { "dia-python", NULL };
-    gchar *startup_file;
-    FILE *fp;
-    PyObject *__main__, *__file__;
-
-    if (Py_IsInitialized ()) {
-        g_warning ("Dia's Python embedding is not designed for concurrency.");
-       return DIA_PLUGIN_INIT_ERROR;
-    }
-    if (!dia_plugin_info_init(info, "Python",
-                             _("Python scripting support"),
-                             dia_py_plugin_can_unload,
-                             dia_py_plugin_unload))
-       return DIA_PLUGIN_INIT_ERROR;
+  char *python_argv[] = { "dia-python", NULL };
+  char *startup_file;
+  FILE *fp;
+  PyObject *__main__, *__file__;
+
+  if (Py_IsInitialized ()) {
+    g_warning ("Dia's Python embedding is not designed for concurrency.");
+    return DIA_PLUGIN_INIT_ERROR;
+  }
+
+  if (!dia_plugin_info_init (info,
+                             "Python",
+                             _("Python scripting support"),
+                             dia_py_plugin_can_unload,
+                             dia_py_plugin_unload)) {
+    return DIA_PLUGIN_INIT_ERROR;
+  }
+
+  Py_SetProgramName ("dia");
+  Py_Initialize ();
 
-    Py_SetProgramName("dia");
-    Py_Initialize();
+  PySys_SetArgv (1, python_argv);
+  /* Sanitize sys.path */
+  PyRun_SimpleString ("import sys; sys.path = filter(None, sys.path)");
 
-    PySys_SetArgv(1, python_argv);
-    /* Sanitize sys.path */
-    PyRun_SimpleString("import sys; sys.path = filter(None, sys.path)");
+  if (on_error_report()) {
+    return DIA_PLUGIN_INIT_ERROR;
+  }
 
-    if (on_error_report())
-       return DIA_PLUGIN_INIT_ERROR;
+  initdia();
 
-    initdia();
-    if (on_error_report())
-       return DIA_PLUGIN_INIT_ERROR;
+  if (on_error_report()) {
+    return DIA_PLUGIN_INIT_ERROR;
+  }
 
 #ifdef G_OS_WIN32
-    PySys_SetObject("stderr", PyDiaError_New (NULL, TRUE));
+  PySys_SetObject("stderr", PyDiaError_New (NULL, TRUE));
 #endif
-    if (g_getenv ("DIA_PYTHON_PATH")) {
-       startup_file = g_build_filename (g_getenv ("DIA_PYTHON_PATH"), "python-startup.py", NULL);
-    } else {
-       startup_file = dia_get_data_directory("python-startup.py");
+  if (g_getenv ("DIA_PYTHON_PATH")) {
+    startup_file = g_build_filename (g_getenv ("DIA_PYTHON_PATH"), "python-startup.py", NULL);
+  } else {
+    startup_file = dia_get_data_directory ("python-startup.py");
+  }
+
+  if (!startup_file) {
+    g_warning ("could not find python-startup.py");
+    return DIA_PLUGIN_INIT_ERROR;
+  }
+
+  /* set __file__ in __main__ so that python-startup.py knows where it is */
+  __main__ = PyImport_AddModule ("__main__");
+  __file__ = PyString_FromString (startup_file);
+  PyObject_SetAttrString (__main__, "__file__", __file__);
+  Py_DECREF (__file__);
+#if defined(G_OS_WIN32) && (PY_VERSION_HEX >= 0x02040000)
+  /* this code should work for every supported Python version, but it is needed
+    * on win32 since Python 2.4 due to mixed runtime issues, i.e.
+    * crashing in PyRun_SimpleFile for python2(5|6)/msvcr(71|90)
+    * It is not enabled by default yet, because I could not get PyGtk using
+    * plug-ins to work at all with 2.5/2.6 */
+  {
+    char *startup_string = NULL;
+    gsize i, length = 0;
+    GError *error = NULL;
+    if (!g_file_get_contents(startup_file, &startup_string, &length, &error)) {
+        g_warning("Python: Couldn't find startup file %s\n%s\n",
+            startup_file, error->message);
+        g_clear_error (&error);
+        g_clear_pointer (&startup_file, g_free);
+        return DIA_PLUGIN_INIT_ERROR;
     }
-    if (!startup_file) {
-       g_warning("could not find python-startup.py");
-       return DIA_PLUGIN_INIT_ERROR;
+    /* PyRun_SimpleString does not like the windows format */
+    for (i = 0; i < length; ++i) {
+      if (startup_string[i] == '\r') {
+        startup_string[i] = '\n';
+      }
     }
 
-    /* set __file__ in __main__ so that python-startup.py knows where it is */
-    __main__ = PyImport_AddModule("__main__");
-    __file__ = PyString_FromString(startup_file);
-    PyObject_SetAttrString(__main__, "__file__", __file__);
-    Py_DECREF(__file__);
-#if defined(G_OS_WIN32) && (PY_VERSION_HEX >= 0x02040000)
-    /* this code should work for every supported Python version, but it is needed
-     * on win32 since Python 2.4 due to mixed runtime issues, i.e.
-     * crashing in PyRun_SimpleFile for python2(5|6)/msvcr(71|90)
-     * It is not enabled by default yet, because I could not get PyGtk using
-     * plug-ins to work at all with 2.5/2.6 */
-    {
-       gchar *startup_string = NULL;
-       gsize i, length = 0;
-       GError *error = NULL;
-       if (!g_file_get_contents(startup_file, &startup_string, &length, &error)) {
-           g_warning("Python: Couldn't find startup file %s\n%s\n",
-                     startup_file, error->message);
-           g_error_free(error);
-           g_free(startup_file);
-           return DIA_PLUGIN_INIT_ERROR;
-       }
-       /* PyRun_SimpleString does not like the windows format */
-       for (i = 0; i < length; ++i)
-           if (startup_string[i] == '\r')
-               startup_string[i] = '\n';
-
-       if (PyRun_SimpleString(startup_string) != 0) {
-           g_warning("Python: Couldn't run startup file %s\n", startup_file);
-       }
-       g_free(startup_string);
+
+    if (PyRun_SimpleString(startup_string) != 0) {
+        g_warning("Python: Couldn't run startup file %s\n", startup_file);
     }
+
+    g_clear_pointer (&startup_string, g_free);
+  }
 #else
-    fp = fopen(startup_file, "r");
-    if (!fp) {
-       g_warning("Python: Couldn't find startup file %s\n", startup_file);
-       g_free(startup_file);
-       return DIA_PLUGIN_INIT_ERROR;
-    }
-    PyRun_SimpleFile(fp, startup_file);
+  fp = fopen (startup_file, "r");
+  if (!fp) {
+    g_warning ("Python: Couldn't find startup file %s\n", startup_file);
+    g_clear_pointer (&startup_file, g_free);
+    return DIA_PLUGIN_INIT_ERROR;
+  }
+  PyRun_SimpleFile (fp, startup_file);
 #endif
-    g_free(startup_file);
+  g_clear_pointer (&startup_file, g_free);
 
-    if (on_error_report())
-       return DIA_PLUGIN_INIT_ERROR;
+  if (on_error_report()) {
+    return DIA_PLUGIN_INIT_ERROR;
+  }
 
-    return DIA_PLUGIN_INIT_OK;
+  return DIA_PLUGIN_INIT_OK;
 }
diff --git a/plug-ins/shape/shape-export.c b/plug-ins/shape/shape-export.c
index ad97d129..e6158504 100644
--- a/plug-ins/shape/shape-export.c
+++ b/plug-ins/shape/shape-export.c
@@ -176,23 +176,23 @@ new_shape_renderer(DiagramData *data, const char *filename)
   sheetname = g_path_get_basename(dirname);
   basename = g_path_get_basename(filename);
   shapename = g_strndup(basename, strlen(basename)-6);
-  g_free(basename);
+  g_clear_pointer (&basename, g_free);
   fullname = g_strdup_printf ("%s - %s", sheetname, shapename);
-  g_free(dirname);
-  g_free(sheetname);
-  g_free(shapename);
+  g_clear_pointer (&dirname, g_free);
+  g_clear_pointer (&sheetname, g_free);
+  g_clear_pointer (&shapename, g_free);
 
   xmlNewChild(renderer->root, NULL, (const xmlChar *)"name", (xmlChar *) fullname);
-  g_free(fullname);
+  g_clear_pointer (&fullname, g_free);
   point = strrchr(filename, '.');
   i = (int)(point-filename);
   point = g_strndup(filename, i);
   png_filename = g_strdup_printf("%s.png",point);
-  g_free(point);
+  g_clear_pointer (&point, g_free);
   basename = g_path_get_basename(png_filename);
   xmlNewChild(renderer->root, NULL, (const xmlChar *)"icon", (xmlChar *) basename);
-  g_free(basename);
-  g_free(png_filename);
+  g_clear_pointer (&basename, g_free);
+  g_clear_pointer (&png_filename, g_free);
   shape_renderer->connection_root = xmlNewChild(renderer->root, NULL, (const xmlChar *)"connections", NULL);
   shape_renderer->design_connection = FALSE;
   xml_node_ptr = xmlNewChild(renderer->root, NULL, (const xmlChar *)"aspectratio",NULL);
@@ -303,12 +303,12 @@ end_render(DiaRenderer *self)
 {
   DiaSvgRenderer *renderer = DIA_SVG_RENDERER (self);
 
-  g_free(renderer->linestyle);
+  g_clear_pointer (&renderer->linestyle, g_free);
   renderer->linestyle = NULL;
 
   xmlSetDocCompressMode(renderer->doc, 0);
   xmlDiaSaveFile(renderer->filename, renderer->doc);
-  g_free(renderer->filename);
+  g_clear_pointer (&renderer->filename, g_free);
   renderer->filename = NULL;
   xmlFreeDoc(renderer->doc);
 }
@@ -625,26 +625,32 @@ export_shape(DiagramData *data, DiaContext *ctx,
     i = (int)(point-filename);
     point = g_strndup(filename, i);
     png_filename = g_strdup_printf("%s.png",point);
-    g_free(point);
+    g_clear_pointer (&point, g_free);
     exportfilter = filter_guess_export_filter(png_filename);
 
     if (!exportfilter) {
-      dia_context_add_message(ctx, _("Can't export PNG icon without export plugin!"));
+      dia_context_add_message (ctx, _("Can't export PNG icon without export plugin!"));
     } else {
       /* get the scaling right */
       old_scaling = data->paper.scaling;
-      scaling_x = 22/((ext->right - ext->left) * 20);
-      scaling_y = 22/((ext->bottom - ext->top) * 20);
-      data->paper.scaling = MIN(scaling_x, scaling_y);
-      exportfilter->export_func(data, ctx, png_filename, diafilename, exportfilter->user_data);
+      scaling_x = 22 / ((ext->right - ext->left) * 20);
+      scaling_y = 22 / ((ext->bottom - ext->top) * 20);
+      data->paper.scaling = MIN (scaling_x, scaling_y);
+      exportfilter->export_func (data,
+                                 ctx,
+                                 png_filename,
+                                 diafilename,
+                                 exportfilter->user_data);
       data->paper.scaling = old_scaling;
     }
-    g_free(png_filename);
+    g_clear_pointer (&png_filename, g_free);
 
     /* create the shape */
-    if((renderer = new_shape_renderer(data, filename))) {
-      data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
-      g_object_unref (renderer);
+    if((renderer = new_shape_renderer (data, filename))) {
+      data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
+
+      g_clear_object (&renderer);
+
       return TRUE;
     }
 
@@ -653,6 +659,7 @@ export_shape(DiagramData *data, DiaContext *ctx,
     return FALSE;
 }
 
+
 static const gchar *extensions[] = { "shape", NULL };
 DiaExportFilter shape_export_filter = {
     N_("Dia Shape File"),
diff --git a/plug-ins/svg/render_svg.c b/plug-ins/svg/render_svg.c
index 2a4e0594..2a3dccca 100644
--- a/plug-ins/svg/render_svg.c
+++ b/plug-ins/svg/render_svg.c
@@ -352,10 +352,11 @@ draw_object(DiaRenderer *self,
     GList *objs = group_objects (object);
 
     if (gm) {
-      gchar *s = dia_svg_from_matrix (gm, renderer->scale);
+      char *s = dia_svg_from_matrix (gm, renderer->scale);
       xmlSetProp(renderer->root, (const xmlChar *)"transform", (xmlChar *) s);
-      g_free (s);
+      g_clear_pointer (&s, g_free);
     }
+
     while (objs) {
       DiaObject *obj = (DiaObject *)objs->data;
 
@@ -366,9 +367,9 @@ draw_object(DiaRenderer *self,
     xmlAddChild (renderer->root, group);
   } else {
     if (matrix) {
-      gchar *s = dia_svg_from_matrix (matrix, renderer->scale);
+      char *s = dia_svg_from_matrix (matrix, renderer->scale);
       xmlSetProp(renderer->root, (const xmlChar *)"transform", (xmlChar *) s);
-      g_free (s);
+      g_clear_pointer (&s, g_free);
     }
 
     object->ops->draw(object, DIA_RENDERER (renderer));
@@ -438,7 +439,7 @@ node_set_text_style (xmlNodePtr      node,
 #if 0 /* would need a unit according to https://bugzilla.mozilla.org/show_bug.cgi?id=707071#c4 */
   tmp = g_strdup_printf("%s;font-size:%s", style,
                        dia_svg_dtostr(d_buf, font_size) );
-  g_free (style);
+  g_clear_pointer (&style, g_free);
   style = tmp;
 #else
   /* font-size as attribute can work like the other length w/o unit */
@@ -560,17 +561,18 @@ draw_rotated_text (DiaRenderer *self, Text *text, Point *center, real angle)
   Point pos = text->position;
   int i;
   xmlNodePtr node_text, node_tspan;
-  gchar d_buf[G_ASCII_DTOSTR_BUF_SIZE];
+  char d_buf[G_ASCII_DTOSTR_BUF_SIZE];
 
   node_text = xmlNewChild(renderer->root, renderer->svg_name_space, (const xmlChar *)"text", NULL);
   /* text 'global' properties  */
   node_set_text_style(node_text, renderer, text->font, text->height, text->alignment, &text->color);
+
   if (angle != 0) {
-     gchar x_buf0[G_ASCII_DTOSTR_BUF_SIZE];
-     gchar y_buf0[G_ASCII_DTOSTR_BUF_SIZE];
-     gchar x_buf1[G_ASCII_DTOSTR_BUF_SIZE];
-     gchar y_buf1[G_ASCII_DTOSTR_BUF_SIZE];
-     gchar *trans;
+    char x_buf0[G_ASCII_DTOSTR_BUF_SIZE];
+    char y_buf0[G_ASCII_DTOSTR_BUF_SIZE];
+    char x_buf1[G_ASCII_DTOSTR_BUF_SIZE];
+    char y_buf1[G_ASCII_DTOSTR_BUF_SIZE];
+    char *trans;
      if (center)
        pos = *center;
      g_ascii_formatd (d_buf, sizeof(d_buf), "%g", angle);
@@ -581,7 +583,7 @@ draw_rotated_text (DiaRenderer *self, Text *text, Point *center, real angle)
      trans = g_strdup_printf ("translate(%s,%s) rotate(%s) translate(%s,%s)",
                              x_buf0, y_buf0, d_buf, x_buf1, y_buf1);
      xmlSetProp(node_text, (const xmlChar *)"transform", (xmlChar *) trans);
-     g_free (trans);
+     g_clear_pointer (&trans, g_free);
   } else {
     dia_svg_dtostr(d_buf, pos.x);
     xmlSetProp(node_text, (const xmlChar *)"x", (xmlChar *) d_buf);
@@ -634,31 +636,38 @@ draw_rotated_image (DiaRenderer *self,
     dia_svg_dtostr(x_buf1, -pos.x);
     dia_svg_dtostr(y_buf1, -pos.y);
     trans = g_strdup_printf ("translate(%s,%s) rotate(%s) translate(%s,%s)",
-                            x_buf0, y_buf0, d_buf, x_buf1, y_buf1);
-    xmlSetProp(node, (const xmlChar *)"transform", (xmlChar *) trans);
-    g_free (trans);
+                             x_buf0, y_buf0, d_buf, x_buf1, y_buf1);
+    xmlSetProp (node, (const xmlChar *)"transform", (xmlChar *) trans);
+    g_clear_pointer (&trans, g_free);
   }
 }
 
+
 /*!
  * \brief Callback function registered for export
  * \ingroup SvgExport
  */
 static gboolean
-export_svg(DiagramData *data, DiaContext *ctx,
-          const gchar *filename, const gchar *diafilename,
-          void* user_data)
+export_svg (DiagramData *data,
+            DiaContext  *ctx,
+            const char  *filename,
+            const char  *diafilename,
+            void        *user_data)
 {
   DiaSvgRenderer *renderer;
 
-  if ((renderer = new_svg_renderer(data, filename))) {
-    data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
-    g_object_unref(renderer);
+  if ((renderer = new_svg_renderer (data, filename))) {
+    data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
+
+    g_clear_object (&renderer);
+
     return TRUE;
   }
+
   return FALSE;
 }
 
+
 static const gchar *extensions[] = { "svg", NULL };
 DiaExportFilter svg_export_filter = {
   N_("Scalable Vector Graphics"),
diff --git a/plug-ins/svg/svg-import.c b/plug-ins/svg/svg-import.c
index 5fc94502..a808cb97 100644
--- a/plug-ins/svg/svg-import.c
+++ b/plug-ins/svg/svg-import.c
@@ -222,6 +222,7 @@ _transform_object (DiaObject *obj, DiaMatrix *m, DiaContext *ctx)
                             obj->type->name);
 }
 
+
 /*!
  * \brief Translate an existing object to a new position
  * The tag 'use' has x and y attributes to position the used object
@@ -230,58 +231,58 @@ _transform_object (DiaObject *obj, DiaMatrix *m, DiaContext *ctx)
 static void
 use_position (DiaObject *obj, xmlNodePtr node, DiaContext *ctx)
 {
-    Point pos = {0, 0};
-    xmlChar *str;
-    Point delta = obj->position;
+  Point pos = {0, 0};
+  xmlChar *str;
+  Point delta = obj->position;
 
-    pos.x = _node_get_real (node, "x", 0.0);
-    pos.y = _node_get_real (node, "y", 0.0);
-    /* not assuming the original is at 0,0 */
-    pos.x += delta.x;
-    pos.y += delta.y;
-    obj->ops->move(obj, &pos);
+  pos.x = _node_get_real (node, "x", 0.0);
+  pos.y = _node_get_real (node, "y", 0.0);
+  /* not assuming the original is at 0,0 */
+  pos.x += delta.x;
+  pos.y += delta.y;
+  dia_object_move (obj, &pos);
 
-    str = xmlGetProp(node, (const xmlChar *)"transform");
-    if (str) {
-        DiaMatrix *m = dia_svg_parse_transform ((char *)str, user_scale);
-
-       if (m) {
-           if (obj->ops->transform) {
-             _transform_object (obj, m, ctx);
-           } else {
-             GPtrArray *props = g_ptr_array_new ();
-
-             PointProperty *pp;
-             RealProperty  *pr;
-
-             /* setting obj_pos is pointless, it is read-only in all objects */
-             prop_list_add_point (props, "obj_pos", &pos);
-             prop_list_add_point (props, "elem_corner", &pos);
-             prop_list_add_real (props, "elem_width", 1.0);
-             prop_list_add_real (props, "elem_height", 1.0);
-
-             obj->ops->get_props (obj, props);
-             /* XXX: try to transform the object without the full matrix  */
-             pp = g_ptr_array_index (props, 0);
-             pp->point_data.x +=  m->x0;
-             pp->point_data.y +=  m->y0;
-             /* XXX: set position a second time, now for non-elements */
-             pp = g_ptr_array_index (props, 1);
-             pp->point_data.x +=  m->x0;
-             pp->point_data.y +=  m->y0;
-
-             pr = g_ptr_array_index (props, 2);
-             pr->real_data *= m->xx;
-             pr = g_ptr_array_index (props, 3);
-             pr->real_data *= m->yy;
-
-             obj->ops->set_props (obj, props);
-             prop_list_free (props);
-           }
-           g_free (m);
-       }
-        xmlFree(str);
+  str = xmlGetProp(node, (const xmlChar *)"transform");
+  if (str) {
+    DiaMatrix *m = dia_svg_parse_transform ((char *) str, user_scale);
+
+    if (m) {
+      if (obj->ops->transform) {
+        _transform_object (obj, m, ctx);
+      } else {
+        GPtrArray *props = g_ptr_array_new ();
+
+        PointProperty *pp;
+        RealProperty  *pr;
+
+        /* setting obj_pos is pointless, it is read-only in all objects */
+        prop_list_add_point (props, "obj_pos", &pos);
+        prop_list_add_point (props, "elem_corner", &pos);
+        prop_list_add_real (props, "elem_width", 1.0);
+        prop_list_add_real (props, "elem_height", 1.0);
+
+        obj->ops->get_props (obj, props);
+        /* XXX: try to transform the object without the full matrix  */
+        pp = g_ptr_array_index (props, 0);
+        pp->point_data.x +=  m->x0;
+        pp->point_data.y +=  m->y0;
+        /* XXX: set position a second time, now for non-elements */
+        pp = g_ptr_array_index (props, 1);
+        pp->point_data.x +=  m->x0;
+        pp->point_data.y +=  m->y0;
+
+        pr = g_ptr_array_index (props, 2);
+        pr->real_data *= m->xx;
+        pr = g_ptr_array_index (props, 3);
+        pr->real_data *= m->yy;
+
+        obj->ops->set_props (obj, props);
+        prop_list_free (props);
+      }
+      g_clear_pointer (&m, g_free);
     }
+    xmlFree(str);
+  }
 }
 
 
@@ -302,13 +303,13 @@ use_position (DiaObject *obj, xmlNodePtr node, DiaContext *ctx)
  */
 static void
 _css_parse_style (DiaSvgStyle *s,
-                  real         user_scale_arg,
-                  gchar       *tag,
-                  gchar       *klass,
-                  gchar       *id,
+                  double       user_scale_arg,
+                  char        *tag,
+                  char        *klass,
+                  char        *id,
                   GHashTable  *style_ht)
 {
-  gchar *style = NULL;
+  char *style = NULL;
 
   /* always try and apply '*' */
   style = g_hash_table_lookup (style_ht, "*");
@@ -327,22 +328,23 @@ _css_parse_style (DiaSvgStyle *s,
   /* build the key in order of importance */
   /* tag.class#id */
   if (id && klass) {
-    gchar *key = g_strdup_printf ("%s.%s#%s", tag, klass, id);
+    char *key = g_strdup_printf ("%s.%s#%s", tag, klass, id);
 
     style = g_hash_table_lookup (style_ht, key);
-    g_free (key);
+    g_clear_pointer (&key, g_free);
     if (!style) {
       /* class#id */
       key = g_strdup_printf (".%s#%s", klass, id);
       style = g_hash_table_lookup (style_ht, key);
-      g_free (key);
+      g_clear_pointer (&key, g_free);
     }
   }
   if (!style && klass) {
-    gchar *key = g_strdup_printf (".%s", klass);
+    char *key = g_strdup_printf (".%s", klass);
     style = g_hash_table_lookup (style_ht, key);
-    g_free (key);
+    g_clear_pointer (&key, g_free);
   }
+
   /* apply most specific style from class lookup */
   if (style) {
     dia_svg_parse_style_string (s, user_scale_arg, style);
@@ -351,18 +353,18 @@ _css_parse_style (DiaSvgStyle *s,
 
   /* apply style from id */
   if (id) {
-    gchar *key = g_strdup_printf ("#%s", id);
+    char *key = g_strdup_printf ("#%s", id);
     style = g_hash_table_lookup (style_ht, key);
     if (style) {
       dia_svg_parse_style_string (s, user_scale_arg, style);
     }
-    g_free (key);
+    g_clear_pointer (&key, g_free);
     key = g_strdup_printf ("%s#%s", tag, id);
     style = g_hash_table_lookup (style_ht, key);
     if (style) {
       dia_svg_parse_style_string (s, user_scale_arg, style);
     }
-    g_free (key);
+    g_clear_pointer (&key, g_free);
   }
 }
 
@@ -383,18 +385,18 @@ _node_css_parse_style (xmlNodePtr   node,
     xmlChar *klass = xmlGetProp (node, (xmlChar *) "class");
 
     if (klass) {
-      gchar **klasses = g_regex_split_simple ("[\\s,;]+",
-                                              (gchar *) klass, 0, 0);
+      char **klasses = g_regex_split_simple ("[\\s,;]+",
+                                             (char *) klass, 0, 0);
       int i = 0;
       while (klasses[i]) {
-        _css_parse_style (gs, user_scale_arg, (gchar *) node->name,
-                          klasses[i], (gchar *) id, style_ht);
+        _css_parse_style (gs, user_scale_arg, (char *) node->name,
+                          klasses[i], (char *) id, style_ht);
         ++i;
       }
       g_strfreev (klasses);
     } else {
-      _css_parse_style (gs, user_scale_arg, (gchar *) node->name,
-                        (gchar *) klass, (gchar *) id, style_ht);
+      _css_parse_style (gs, user_scale_arg, (char *) node->name,
+                        (char *) klass, (char *) id, style_ht);
     }
 
     if (id) {
@@ -409,22 +411,27 @@ _node_css_parse_style (xmlNodePtr   node,
 
 
 static void
-_set_pattern_from_key (DiaObject *obj, BoolProperty *bprop,
-                      GHashTable *pattern_ht, const gchar *key)
+_set_pattern_from_key (DiaObject    *obj,
+                       BoolProperty *bprop,
+                       GHashTable   *pattern_ht,
+                       const char   *key)
 {
   ObjectChange *change = NULL;
   DiaPattern *pattern = g_hash_table_lookup (pattern_ht, key);
+
   if (pattern) {
     change = dia_object_set_pattern (obj, pattern);
     /* activate "show_background" */
     bprop->bool_data = TRUE;
   }
+
   if (change) { /* throw it away, no one needs it here  */
     change->free (change);
-    g_free (change);
+    g_clear_pointer (&change, g_free);
   }
 }
 
+
 /*!
  * \brief apply SVG style to object
  * Styling with SVG is a complicated thing. The style can be given with:
@@ -456,7 +463,7 @@ apply_style(DiaObject *obj, xmlNodePtr node, DiaSvgStyle *parent_style,
          DiaMatrix *m = dia_svg_parse_transform ((char *)str, user_scale);
          if (m) {
            transform_length (&scale, m);
-           g_free (m);
+           g_clear_pointer (&m, g_free);
          }
          xmlFree(str);
       }
@@ -522,27 +529,27 @@ apply_style(DiaObject *obj, xmlNodePtr node, DiaSvgStyle *parent_style,
       /* apply pattern, gradient if any */
       str = xmlGetProp(node, (const xmlChar *)"fill");
       if (str) {
-       const char *left = strstr ((const char*)str, "url(#");
-       const char *right = strrchr ((const char*)str, ')');
-       if (left && right) {
-         gchar *key = g_strndup (left + 5, right - left - 5);
-         _set_pattern_from_key (obj, bprop, pattern_ht, key);
-         g_free (key);
-       }
-       xmlFree(str);
+        const char *left = strstr ((const char*)str, "url(#");
+        const char *right = strrchr ((const char*)str, ')');
+        if (left && right) {
+          char *key = g_strndup (left + 5, right - left - 5);
+          _set_pattern_from_key (obj, bprop, pattern_ht, key);
+          g_clear_pointer (&key, g_free);
+        }
+        xmlFree(str);
       } else if (gs->fill == DIA_SVG_COLOUR_NONE) {
         /* check the style again, it might contain a pattern */
-       str = xmlGetProp(node, (const xmlChar*)"style");
-       if (str) {
-         const char *left = strstr ((const char*)str, "fill:url(#");
-         const char *right = left ? strrchr (left, ')') : NULL;
-         if (left && right) {
-           gchar *key = g_strndup (left + 10, right - left - 10);
-           _set_pattern_from_key (obj, bprop, pattern_ht, key);
-           g_free (key);
-         }
-         xmlFree (str);
-       }
+        str = xmlGetProp(node, (const xmlChar*)"style");
+        if (str) {
+          const char *left = strstr ((const char*)str, "fill:url(#");
+          const char *right = left ? strrchr (left, ')') : NULL;
+          if (left && right) {
+            char *key = g_strndup (left + 10, right - left - 10);
+            _set_pattern_from_key (obj, bprop, pattern_ht, key);
+            g_clear_pointer (&key, g_free);
+          }
+          xmlFree (str);
+        }
       }
 
       eprop = g_ptr_array_index(props,5);
@@ -557,10 +564,10 @@ apply_style(DiaObject *obj, xmlNodePtr node, DiaSvgStyle *parent_style,
       else
        eprop->common.experience |= PXP_NOTSET;
 
-      obj->ops->set_props(obj, props);
+  dia_object_set_properties (obj, props);
 
-      g_clear_object (&gs->font);
-      g_free (gs);
+  g_clear_object (&gs->font);
+  g_clear_pointer (&gs, g_free);
 }
 
 /*!
@@ -707,7 +714,7 @@ read_path_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
        new_obj = otype->ops->create(NULL, bcd, &h1, &h2);
        if (!closed)
          reset_arrows (new_obj);
-       g_free(bcd);
+       g_clear_pointer (&bcd, g_free);
        apply_style(new_obj, node, parent_style, style_ht, pattern_ht, TRUE);
        list = g_list_append (list, new_obj);
 
@@ -717,14 +724,17 @@ read_path_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
       unparsed = NULL;
     } while (pathdata);
 
-    if (bezpoints)
-      g_array_free (bezpoints, TRUE);
-    if (matrix)
-      g_free (matrix);
+  if (bezpoints) {
+    g_array_free (bezpoints, TRUE);
+  }
 
-    xmlFree (str);
+  if (matrix) {
+    g_clear_pointer (&matrix, g_free);
+  }
 
-    return list;
+  xmlFree (str);
+
+  return list;
 }
 
 /*!
@@ -805,7 +815,7 @@ read_text_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
     if (!any_tspan) {
       str = xmlNodeGetContent(node);
       /* so no valid multiline */
-      g_free (multiline);
+      g_clear_pointer (&multiline, g_free);
       multiline = NULL;
     }
     if(str || multiline) {
@@ -820,7 +830,7 @@ read_text_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
        gs->font = dia_font_new_from_legacy_name("Courier");
       }
       prop = g_ptr_array_index(props, 0);
-      g_free(prop->text_data);
+      g_clear_pointer (&prop->text_data, g_free);
       prop->text_data = str ? g_strdup((char *) str) : multiline;
       if (!preserve_space)
         prop->text_data = g_strstrip (prop->text_data); /* modifies in-place */
@@ -864,8 +874,8 @@ read_text_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
         _transform_object (new_obj, matrix, ctx);
     }
     g_clear_object (&gs->font);
-    g_free (gs);
-    g_free (matrix);
+    g_clear_pointer (&gs, g_free);
+    g_clear_pointer (&matrix, g_free);
 
     return list;
 }
@@ -907,7 +917,7 @@ read_poly_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
     str = xmlGetProp(node, (const xmlChar *)"points");
     if (!str) {
       g_warning ("SVG: '%s' without points", node->name);
-      g_free (matrix);
+      g_clear_pointer (&matrix, g_free);
       return list;
     }
     tmp = (char *) str;
@@ -930,12 +940,12 @@ read_poly_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
     for (i = 0; i < pcd->num_points; i++) {
       points[i].x = rarr[2*i];
       points[i].y = rarr[2*i+1];
-      if (matrix)
-       transform_point (&points[i], matrix);
+      if (matrix) {
+        transform_point (&points[i], matrix);
+      }
     }
-    g_array_free(arr, TRUE);
-    if (matrix)
-      g_free (matrix);
+    g_array_free (arr, TRUE);
+    g_clear_pointer (&matrix, g_free);
 
     pcd->points = points;
     new_obj = otype->ops->create(NULL, pcd,
@@ -943,8 +953,8 @@ read_poly_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
     reset_arrows (new_obj);
     apply_style(new_obj, node, parent_style, style_ht, pattern_ht, TRUE);
     list = g_list_append (list, new_obj);
-    g_free(points);
-    g_free(pcd);
+    g_clear_pointer (&points, g_free);
+    g_clear_pointer (&pcd, g_free);
 
     return list;
 }
@@ -997,7 +1007,7 @@ read_ellipse_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
   new_obj->ops->set_props(new_obj, props);
   if (matrix) {
     _transform_object (new_obj, matrix, ctx);
-    g_free (matrix);
+    g_clear_pointer (&matrix, g_free);
   }
   prop_list_free(props);
   return g_list_append (list, new_obj);
@@ -1053,7 +1063,7 @@ read_line_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
 
   if (matrix) {
     _transform_object (new_obj, matrix, ctx);
-    g_free (matrix);
+    g_clear_pointer (&matrix, g_free);
   }
 
   return g_list_append (list, new_obj);
@@ -1139,7 +1149,7 @@ read_rect_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
 
   if (matrix) {
     _transform_object (new_obj, matrix, ctx);
-    g_free (matrix);
+    g_clear_pointer (&matrix, g_free);
   }
   return list;
 }
@@ -1179,31 +1189,31 @@ read_image_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
       const char* data = strchr((char *)str, ',');
 
       if (data) {
-       GdkPixbuf *pixbuf = pixbuf_decode_base64 (data+1);
+        GdkPixbuf *pixbuf = pixbuf_decode_base64 (data+1);
 
-       if (pixbuf) {
-         ObjectChange *change;
+        if (pixbuf) {
+          ObjectChange *change;
 
-         new_obj = create_standard_image(x, y, width, height, NULL);
-         change = dia_object_set_pixbuf (new_obj, pixbuf);
-         if (change) { /* throw it away, no one needs it here  */
-           change->free (change);
-            g_free (change);
+          new_obj = create_standard_image(x, y, width, height, NULL);
+          change = dia_object_set_pixbuf (new_obj, pixbuf);
+          if (change) { /* throw it away, no one needs it here  */
+            change->free (change);
+            g_clear_pointer (&change, g_free);
           }
-         g_object_unref (pixbuf);
-       }
+          g_clear_object (&pixbuf);
+        }
       }
     } else {
-      gchar *filename = g_filename_from_uri((gchar *) str, NULL, NULL);
+      char *filename = g_filename_from_uri ((char *) str, NULL, NULL);
       if (!filename || !g_path_is_absolute (filename)) {
-       /* if image file path is relative use the main path */
-       gchar *dir = g_path_get_dirname (filename_svg);
-       gchar *absfn = g_build_path (G_DIR_SEPARATOR_S,
-                                    dir, filename ? filename : (gchar *)str, NULL);
-
-       g_free (filename);
-       g_free (dir);
-       filename = absfn;
+        /* if image file path is relative use the main path */
+        char *dir = g_path_get_dirname (filename_svg);
+        char *absfn = g_build_path (G_DIR_SEPARATOR_S,
+                                    dir, filename ? filename : (char *) str, NULL);
+
+        g_clear_pointer (&filename, g_free);
+        g_clear_pointer (&dir, g_free);
+        filename = absfn;
       }
       /* Importing svg as "Misc - Diagram" should produce better results than GdkPixbuf rendering */
       if (filename && g_strrstr (filename, ".svg")) {
@@ -1226,15 +1236,16 @@ read_image_svg(xmlNodePtr node, DiaSvgStyle *parent_style,
       } else {
        new_obj = create_standard_image(x, y, width, height, filename ? filename : "<broken>");
       }
-      g_free(filename);
+      g_clear_pointer (&filename, g_free);
     }
     xmlFree(str);
   }
 
   if (matrix && new_obj) {
     _transform_object (new_obj, matrix, ctx);
-    g_free (matrix);
+    g_clear_pointer (&matrix, g_free);
   }
+
   if (new_obj)
     return g_list_append (list, new_obj);
 
@@ -1348,12 +1359,12 @@ read_gradient (xmlNodePtr node, DiaSvgStyle *parent_gs, GHashTable  *pattern_ht,
     }
     child = child->next;
   }
-  if (matrix)
-    g_free (matrix);
+  g_clear_pointer (&matrix, g_free);
 
   return pat;
 }
 
+
 /*!
  * \brief Parse the CSS style block of the SVG
  *
@@ -1381,16 +1392,16 @@ read_style (xmlNodePtr node, GHashTable *ht)
        * To the left there might be referenced parents in the tree restricting
        * the effect of the key but that's just too complicated for Dia's SVG ...
        */
-      gchar *key = g_match_info_fetch (info, 1);
-      gchar *val = g_match_info_fetch (info, 2);
-      const gchar *former;
+      char *key = g_match_info_fetch (info, 1);
+      char *val = g_match_info_fetch (info, 2);
+      const char *former;
 
       /* multiple occurrences chain up to a single style string */
       former = g_hash_table_lookup (ht, key);
       if (former) {
-       gchar *tmp = val;
+        char *tmp = val;
         val = g_strdup_printf ("%s;%s", former, val);
-       g_free (tmp);
+        g_clear_pointer (&tmp, g_free);
       }
       /* hashtable taking ownership */
       g_hash_table_insert (ht, key, val);
@@ -1400,10 +1411,12 @@ read_style (xmlNodePtr node, GHashTable *ht)
     g_regex_unref (regex);
     xmlFree (str);
   }
+
   if (style_type)
     xmlFree (style_type);
 }
 
+
 /* GFunc for foreach */
 static void
 add_def (gpointer       data,
@@ -1411,15 +1424,16 @@ add_def (gpointer       data,
 {
   DiaObject  *obj = (DiaObject *)data;
   GHashTable *defs_ht = (GHashTable *)user_data;
-  gchar *id = dia_object_get_meta (obj, "id");
+  char *id = dia_object_get_meta (obj, "id");
   if (id) { /* pass ownership of name and object */
     g_hash_table_insert (defs_ht, id, obj);
   } else {
     obj->ops->destroy (obj);
-    g_free (obj);
+    g_clear_pointer (&obj, g_free);
   }
 }
 
+
 /*!
  * \brief Parse and set global user scale
  *
@@ -1531,16 +1545,16 @@ _node_read_viewbox (xmlNodePtr root, DiaMatrix **mat)
  */
 static GList*
 read_items (xmlNodePtr   startnode,
-           DiaSvgStyle *parent_gs,
-           GHashTable  *defs_ht,
-           GHashTable  *style_ht,
-           GHashTable  *pattern_ht,
-           const gchar *filename_svg,
-           DiaContext  *ctx)
+            DiaSvgStyle *parent_gs,
+            GHashTable  *defs_ht,
+            GHashTable  *style_ht,
+            GHashTable  *pattern_ht,
+            const char  *filename_svg,
+            DiaContext  *ctx)
 {
   xmlNodePtr node;
   GList *items = NULL;
-  gchar *comment = NULL;
+  char *comment = NULL;
 
 
   for (node = startnode; node != NULL; node = node->next) {
@@ -1552,12 +1566,12 @@ read_items (xmlNodePtr   startnode,
 
     if (xmlIsBlankNode(node)) continue;
     if (node->type == XML_COMMENT_NODE) {
-      if (!comment)
-       comment = g_strdup ((gchar *)node->content);
-      else {
-       gchar *prev = comment;
-       comment = g_strjoin ("\n", comment, (gchar *)node->content, NULL);
-       g_free (prev);
+      if (!comment) {
+        comment = g_strdup ((char *) node->content);
+      } else {
+        char *prev = comment;
+        comment = g_strjoin ("\n", comment, (char *) node->content, NULL);
+        g_clear_pointer (&prev, g_free);
       }
       continue;
     }
@@ -1599,8 +1613,8 @@ read_items (xmlNodePtr   startnode,
        obj = group;
       }
       g_clear_object (&group_gs->font);
-      g_free (group_gs);
-      g_free (matrix);
+      g_clear_pointer (&group_gs, g_free);
+      g_clear_pointer (&matrix, g_free);
     } else if (!xmlStrcmp(node->name, (const xmlChar *)"symbol")) {
       /* ignore 'viewBox' and 'preserveAspectRatio' */
       GList *moreitems = read_items (node->xmlChildrenNode, parent_gs,
@@ -1764,14 +1778,13 @@ read_items (xmlNodePtr   startnode,
        xmlFree (val);
       }
       if (comment) {
-       dia_object_set_meta (obj, "comment", (char *)comment);
-       g_free (comment);
-       comment = NULL;
+        dia_object_set_meta (obj, "comment", (char *)comment);
+        g_clear_pointer (&comment, g_free);
       }
     }
   }
   /* just to be sure */
-  g_free (comment);
+  g_clear_pointer (&comment, g_free);
   return items;
 }
 
@@ -1819,27 +1832,27 @@ read_defs (xmlNodePtr   startnode,
        * Less commonly used are normal objects which could be supported here.
        */
       for (list = defs; list != NULL; list = g_list_next (list)) {
-       DiaObject *otemp = list->data;
-       gchar *id;
-
-       id = dia_object_get_meta (otemp, "id");
-       if (id) {
-         /* pass ownership of name and object */
-         g_hash_table_insert (defs_ht, id, otemp);
-       } else if (IS_GROUP (otemp)) {
-         /* defs in _unnamed_ groups, I don't get the
-          * benefit but must have seen it in the wild.
-          */
-         GList *moredefs = group_objects (otemp);
-
-         g_list_foreach (moredefs, add_def, defs_ht);
-         group_destroy_shallow (otemp);
-       } else {
-         /* just loose the object */
-         otemp->ops->destroy (otemp);
-         g_free (otemp);
-         list->data = NULL;
-       }
+        DiaObject *otemp = list->data;
+        char *id;
+
+        id = dia_object_get_meta (otemp, "id");
+        if (id) {
+          /* pass ownership of name and object */
+          g_hash_table_insert (defs_ht, id, otemp);
+        } else if (IS_GROUP (otemp)) {
+          /* defs in _unnamed_ groups, I don't get the
+          * benefit but must have seen it in the wild.
+          */
+          GList *moredefs = group_objects (otemp);
+
+          g_list_foreach (moredefs, add_def, defs_ht);
+          group_destroy_shallow (otemp);
+        } else {
+          /* just loose the object */
+          otemp->ops->destroy (otemp);
+          g_clear_pointer (&otemp, g_free);
+          list->data = NULL;
+        }
       }
       /* kind of greedy */
       read_defs (node->xmlChildrenNode, parent_gs,
@@ -1864,11 +1877,12 @@ read_defs (xmlNodePtr   startnode,
       dia_svg_parse_style (node, &group_gs, user_scale);
 
       read_defs (node->xmlChildrenNode, &group_gs,
-                defs_ht, style_ht, pattern_ht,
-                filename_svg, ctx);
+                 defs_ht, style_ht, pattern_ht,
+                 filename_svg, ctx);
 
-      if (group_gs.font)
-        g_object_unref (group_gs.font);
+      if (group_gs.font) {
+        g_clear_object (&group_gs.font);
+      }
     }
   }
 }
@@ -2098,14 +2112,16 @@ import_svg (xmlDocPtr doc, DiagramData *dia,
    * preserve the drawing order. Also we should keep the groups intact
    * to preserve potential transformations.
    */
-  if (num_items == 1)
+  if (num_items == 1) {
     groups_to_layers = FALSE;
+  }
+
   for (item = items; groups_to_layers && item != NULL; item = g_list_next (item)) {
     DiaObject *obj = (DiaObject *)item->data;
-    gchar *name;
+    char *name;
 
     if (IS_GROUP(obj) && ((name = dia_object_get_meta (obj, "id")) != NULL))
-      g_free (name);
+      g_clear_pointer (&name, g_free);
     else
       groups_to_layers = FALSE;
   }
@@ -2113,11 +2129,11 @@ import_svg (xmlDocPtr doc, DiagramData *dia,
     DiaObject *obj = (DiaObject *)item->data;
 
     if (groups_to_layers) {
-      gchar *name = dia_object_get_meta (obj, "id");
+      char *name = dia_object_get_meta (obj, "id");
       /* new_layer() is taking ownership of the name */
       DiaLayer *layer = dia_layer_new (name, dia);
 
-      g_free (name);
+      g_clear_pointer (&name, g_free);
 
       /* keep the group for potential transformation */
       dia_layer_add_object (layer, obj);
@@ -2127,7 +2143,6 @@ import_svg (xmlDocPtr doc, DiagramData *dia,
       dia_layer_add_object (dia->active_layer, obj);
       dia_layer_update_extents (dia->active_layer);
     }
-
   }
 
   g_list_free (items);
@@ -2144,13 +2159,13 @@ import_svg (xmlDocPtr doc, DiagramData *dia,
 
 /* interface from filter.h */
 
-static const gchar *extensions[] = {"svg", "svgz", NULL };
+static const char *extensions[] = { "svg", "svgz", NULL };
 DiaImportFilter svg_import_filter = {
-       N_("Scalable Vector Graphics"),
-       extensions,
-       import_file_svg,
-       NULL, /* user_data */
-       "dia-svg",
-       0, /* flags */
-       import_memory_svg
+  N_("Scalable Vector Graphics"),
+  extensions,
+  import_file_svg,
+  NULL, /* user_data */
+  "dia-svg",
+  0, /* flags */
+  import_memory_svg
 };
diff --git a/plug-ins/vdx/vdx-export.c b/plug-ins/vdx/vdx-export.c
index 37fa04fe..764d297b 100644
--- a/plug-ins/vdx/vdx-export.c
+++ b/plug-ins/vdx/vdx-export.c
@@ -107,9 +107,11 @@ struct _VDXRenderer
 
 static void vdx_renderer_class_init (VDXRendererClass *klass);
 
-static gboolean export_vdx(DiagramData *data, DiaContext *ctx,
-                          const gchar *filename, const gchar *diafilename,
-                          void* user_data);
+static gboolean export_vdx (DiagramData *data,
+                            DiaContext  *ctx,
+                            const char  *filename,
+                            const char  *diafilename,
+                            void        *user_data);
 
 static int
 vdxCheckColor(VDXRenderer *renderer, Color *color);
@@ -696,7 +698,7 @@ static void draw_polyline(DiaRenderer *self, Point *points, int num_points,
     /* Free up list entries */
     g_slist_free(Geom.any.children);
     g_slist_free(Shape.any.children);
-    g_free(LineTo);
+    g_clear_pointer (&LineTo, g_free);
 }
 
 static void
@@ -811,15 +813,16 @@ _polygon (DiaRenderer *self,
        Shape.any.children = g_slist_append(Shape.any.children, &Line);
     Shape.any.children = g_slist_append(Shape.any.children, &Geom);
 
-    /* Write out XML */
-    vdx_write_object(renderer->file, renderer->xml_depth, &Shape);
+  /* Write out XML */
+  vdx_write_object (renderer->file, renderer->xml_depth, &Shape);
 
-    /* Free up list entries */
-    g_slist_free(Geom.any.children);
-    g_slist_free(Shape.any.children);
-    g_free(LineTo);
+  /* Free up list entries */
+  g_slist_free (Geom.any.children);
+  g_slist_free (Shape.any.children);
+  g_clear_pointer (&LineTo, g_free);
 }
 
+
 /** Render a Dia filled polygon
  * @param self a renderer
  * @param points corners of polygon
@@ -1464,25 +1467,25 @@ static void draw_image(DiaRenderer *self,
     Shape.any.children = g_slist_append(Shape.any.children, &ForeignData);
     ForeignData.any.children = g_slist_append(ForeignData.any.children, &text);
 
-    /* Write out XML */
-    vdx_write_object(renderer->file, renderer->xml_depth, &Shape);
+  /* Write out XML */
+  vdx_write_object (renderer->file, renderer->xml_depth, &Shape);
 
-    /* Free up list entries */
-    g_slist_free(ForeignData.any.children);
-    g_slist_free(Shape.any.children);
+  /* Free up list entries */
+  g_slist_free (ForeignData.any.children);
+  g_slist_free (Shape.any.children);
 
-    /* And the Base64 data */
-    g_free(text.text);
+  /* And the Base64 data */
+  g_clear_pointer (&text.text, g_free);
 }
 
+
 /** Convert Dia colour to hex string
  * @param c a colour
  * @returns string in form #000000
  * @note static buffer overwritten with next call; not thread-safe
  */
-
 const char *
-vdx_string_color(const Color c)
+vdx_string_color (const Color c)
 {
     static char buf[8];
     sprintf(buf, "#%.2X%.2X%.2X",
@@ -1752,6 +1755,7 @@ write_trailer(DiagramData *data, VDXRenderer *renderer)
     fprintf(file, "</VisioDocument>\n");
 }
 
+
 /** Write VDX file
  * @param data diagram data
  * @param filename output file (should check suffix)
@@ -1759,11 +1763,12 @@ write_trailer(DiagramData *data, VDXRenderer *renderer)
  * @param user_data user data (unused)
  * @note Must know if 2002 or 2003 before start
  */
-
 static gboolean
-export_vdx(DiagramData *data, DiaContext *ctx,
-          const gchar *filename, const gchar *diafilename,
-          void* user_data)
+export_vdx (DiagramData *data,
+            DiaContext  *ctx,
+            const char  *filename,
+            const char  *diafilename,
+            void        *user_data)
 {
     FILE *file;
     VDXRenderer *renderer;
@@ -1822,26 +1827,28 @@ export_vdx(DiagramData *data, DiaContext *ctx,
 
     dia_renderer_end_render (DIA_RENDERER (renderer));
 
-    /* Done */
+  /* Done */
 
-    write_trailer(data, renderer);
+  write_trailer (data, renderer);
 
-    g_object_unref(renderer);
+  g_clear_object (&renderer);
 
-    /* dont screw Dia's global state */
-    setlocale(LC_NUMERIC, old_locale);
+  /* dont screw Dia's global state */
+  setlocale (LC_NUMERIC, old_locale);
 
-    if (fclose(file) != 0) {
-       dia_context_add_message_with_errno (ctx, errno, _("Saving file '%s' failed."),
-                                           dia_context_get_filename(ctx));
-       return FALSE;
-    }
-    return TRUE;
+  if (fclose (file) != 0) {
+    dia_context_add_message_with_errno (ctx, errno,
+                                        _("Saving file '%s' failed."),
+                                        dia_context_get_filename (ctx));
+    return FALSE;
+  }
+
+  return TRUE;
 }
 
 /* interface from filter.h */
 
-static const gchar *extensions[] = { "vdx", NULL };
+static const char *extensions[] = { "vdx", NULL };
 DiaExportFilter vdx_export_filter = {
   N_("Visio XML format"),
   extensions,
diff --git a/plug-ins/vdx/vdx-import.c b/plug-ins/vdx/vdx-import.c
index 73841882..519498ae 100644
--- a/plug-ins/vdx/vdx-import.c
+++ b/plug-ins/vdx/vdx-import.c
@@ -151,7 +151,7 @@ create_vdx_beziergon(int num_points,
     new_obj = otype->ops->create(NULL, bcd,
                                 &h1, &h2);
 
-    g_free(bcd);
+    g_clear_pointer (&bcd, g_free);
 
     /* Convert all points to cusps - not in API */
 
@@ -445,7 +445,7 @@ free_children(void *p)
         {
             if (!list->data) continue;
             free_children(list->data);
-            g_free(list->data);
+            g_clear_pointer (&list->data, g_free);
         }
         g_slist_free(list);
     }
@@ -1015,8 +1015,8 @@ plot_polyline(const struct vdx_Geom *Geom, const struct vdx_XForm *XForm,
     }
     if (newobj)
         vdx_simple_properties(newobj, Fill, Line, theDoc, ctx);
-    g_free(end_arrow_p);
-    g_free(start_arrow_p);
+    g_clear_pointer (&end_arrow_p, g_free);
+    g_clear_pointer (&start_arrow_p, g_free);
     return newobj;
 }
 
@@ -1573,13 +1573,13 @@ plot_bezier(const struct vdx_Geom *Geom, const struct vdx_XForm *XForm,
                     g_debug("Empty polyline");
             }
         }
-        g_free(points);
+        g_clear_pointer (&points, g_free);
     }
-    g_free(bezpoints);
+    g_clear_pointer (&bezpoints, g_free);
     if (newobj)
         vdx_simple_properties(newobj, Fill, Line, theDoc, ctx);
-    g_free(end_arrow_p);
-    g_free(start_arrow_p);
+    g_clear_pointer (&end_arrow_p, g_free);
+    g_clear_pointer (&start_arrow_p, g_free);
     return newobj;
 }
 
@@ -1970,11 +1970,11 @@ plot_nurbs(const struct vdx_Geom *Geom, const struct vdx_XForm *XForm,
 
     newobj = create_standard_polyline(num_points, points, end_arrow_p, start_arrow_p);
 
-    g_free(end_arrow_p);
-    g_free(start_arrow_p);
-    g_free(control);
-    g_free(weight);
-    g_free(knot);
+    g_clear_pointer (&end_arrow_p, g_free);
+    g_clear_pointer (&start_arrow_p, g_free);
+    g_clear_pointer (&control, g_free);
+    g_clear_pointer (&weight, g_free);
+    g_clear_pointer (&knot, g_free);
 
     vdx_simple_properties(newobj, Fill, Line, theDoc, ctx);
     return newobj;
@@ -2297,11 +2297,10 @@ plot_text(const struct vdx_Text *Text, const struct vdx_XForm *XForm,
 
     /* set up the text property by including all children */
     tprop->text_data = g_strdup(text->text);
-    while((text = find_child_next(vdx_types_text, Text, text)))
-    {
-        char *s = tprop->text_data;
-        tprop->text_data = g_strconcat(tprop->text_data, text->text, NULL);
-        g_free(s);
+    while ((text = find_child_next (vdx_types_text, Text, text))) {
+      char *s = tprop->text_data;
+      tprop->text_data = g_strconcat (tprop->text_data, text->text, NULL);
+      g_clear_pointer (&s, g_free);
     }
 
     /* Fix Unicode line breaks */
@@ -2620,40 +2619,38 @@ vdx_plot_shape(struct vdx_Shape *Shape, GSList *objects,
         if (Geom->NoLine) Line = 0;
 
         more = Geom->any.children;
-        do
-        {
-           DiaObject *object = plot_geom(Geom, XForm, XForm1D, Fill, Line,
-                                          Foreign, ForeignData, theDoc, &more,
-                                          &current, ctx);
+        do {
+          DiaObject *object = plot_geom (Geom, XForm, XForm1D, Fill, Line,
+                                         Foreign, ForeignData, theDoc, &more,
+                                         &current, ctx);
             /* object can be NULL for Text */
-           if (object)
-           {
-               gchar *id = g_strdup_printf ("%d", Shape->ID);
-               objects = g_slist_append(objects, object);
-               dia_object_set_meta (object, "id", id);
-               g_free (id);
-           }
-            if (more && theDoc->debug_comments)
-            {
-                g_debug("Additional Geom");
-            }
+          if (object) {
+            char *id = g_strdup_printf ("%d", Shape->ID);
+            objects = g_slist_append (objects, object);
+            dia_object_set_meta (object, "id", id);
+            g_clear_pointer (&id, g_free);
+          }
+
+          if (more && theDoc->debug_comments) {
+              g_debug ("Additional Geom");
+          }
         } while (more);
+
         /* Yes, you can have multiple (disconnected) Geoms */
         Geom = find_child_next(vdx_types_Geom, Shape, Geom);
     }
+
     /* Text always after the object it's attached to,
        so it appears on top */
-    if (Text && find_child(vdx_types_text, Text))
-    {
-        DiaObject *object = plot_text(Text, XForm, Char, Para,
-                                      TextBlock, TextXForm, theDoc);
-       if (object)
-       {
-           gchar *id = g_strdup_printf ("%d", Shape->ID);
-            objects = g_slist_append(objects, object);
-           dia_object_set_meta (object, "id", id);
-           g_free (id);
-       }
+    if (Text && find_child (vdx_types_text, Text)) {
+      DiaObject *object = plot_text (Text, XForm, Char, Para,
+                                     TextBlock, TextXForm, theDoc);
+      if (object) {
+        char *id = g_strdup_printf ("%d", Shape->ID);
+        objects = g_slist_append (objects, object);
+        dia_object_set_meta (object, "id", id);
+        g_clear_pointer (&id, g_free);
+      }
     }
 
     /* Wipe the child XForm list to avoid double-free */
@@ -2919,7 +2916,7 @@ vdx_free(VDXDocument *theDoc)
     }
     if (theDoc->LayerNames) g_array_free(theDoc->LayerNames, TRUE);
     if (theDoc->PageLayers) g_array_free(theDoc->PageLayers, TRUE);
-    g_free(theDoc->debug_shape_ids);
+    g_clear_pointer (&theDoc->debug_shape_ids, g_free);
 }
 
 
@@ -2930,7 +2927,7 @@ vdx_free(VDXDocument *theDoc)
  * @returns TRUE if successful, FALSE otherwise
  */
 static gboolean
-import_vdx(const gchar *filename, DiagramData *dia, DiaContext *ctx, void* user_data)
+import_vdx (const char *filename, DiagramData *dia, DiaContext *ctx, void* user_data)
 {
     xmlErrorPtr error_xml = NULL;
     xmlDocPtr doc = xmlDoParseFile(filename, &error_xml);
@@ -3042,7 +3039,7 @@ import_vdx(const gchar *filename, DiagramData *dia, DiaContext *ctx, void* user_
 
 /* interface from filter.h */
 
-static const gchar *extensions[] = {"vdx", NULL };
+static const char *extensions[] = {"vdx", NULL };
 DiaImportFilter vdx_import_filter = {
     N_("Visio XML File Format"),
     extensions,
diff --git a/plug-ins/wpg/wpg-import.c b/plug-ins/wpg/wpg-import.c
index 359b8aac..f0937579 100644
--- a/plug-ins/wpg/wpg-import.c
+++ b/plug-ins/wpg/wpg-import.c
@@ -309,8 +309,10 @@ import_object(DiaRenderer* self, DiagramData *dia,
       g_warning ("Uknown type %i", type);
       break;
   } /* switch */
-  g_free (points);
-  DIAG_NOTE(g_message("Type %d Num pts %d Size %d", type, iNum, iSize));
+
+  g_clear_pointer (&points, g_free);
+
+  DIAG_NOTE (g_message ("Type %d Num pts %d Size %d", type, iNum, iSize));
 }
 
 static void
@@ -429,8 +431,10 @@ _render_bmp (WpgImportRenderer *ren, WPGBitmap2 *bmp, FILE *f, int len)
                                (bmp->Bottom - bmp->Top) / WPU_PER_DCM,
                                image);
     }
-    g_object_unref (pixbuf);
-    g_object_unref (image);
+
+    g_clear_object (&pixbuf);
+    g_clear_object (&image);
+
     return bRet;
   }
 #undef PUT_PIXEL
@@ -585,7 +589,7 @@ import_data (const gchar *filename, DiagramData *dia, DiaContext *ctx, void* use
             pData = g_new(guchar, iSize);
             bRet = (iSize == (int)fread(pData, 1, iSize, f));
             import_object(DIA_RENDERER(ren), dia, rh.Type, iSize, pData);
-            g_free(pData);
+            g_clear_pointer (&pData, g_free);
           }
           break;
         case WPG_COLORMAP:
@@ -664,11 +668,15 @@ import_data (const gchar *filename, DiagramData *dia, DiaContext *ctx, void* use
     }
     while ((iSize > 0) && (bRet));
 
-    if (!bRet)
-      dia_context_add_message (ctx, _("Unexpected end of file. WPG type %d, size %d.\n"),
-                              rh.Type, iSize);
-    if (ren->pPal)
-      g_free(ren->pPal);
+    if (!bRet) {
+      dia_context_add_message (ctx,
+                               _("Unexpected end of file. WPG type %d, size %d.\n"),
+                               rh.Type,
+                               iSize);
+    }
+
+    g_clear_pointer (&ren->pPal, g_free);
+
     /* transfer to diagram data */
     {
       DiaObject *objs = dia_import_renderer_get_objects (DIA_RENDERER(ren));
@@ -679,10 +687,12 @@ import_data (const gchar *filename, DiagramData *dia, DiaContext *ctx, void* use
         bRet = FALSE;
       }
     }
-    g_object_unref (ren);
+    g_clear_object (&ren);
   } /* bRet */
 
-  if (f)
-    fclose(f);
+  if (f) {
+    fclose (f);
+  }
+
   return bRet;
 }
diff --git a/plug-ins/wpg/wpg.c b/plug-ins/wpg/wpg.c
index 2b7b33c8..77210c2f 100644
--- a/plug-ins/wpg/wpg.c
+++ b/plug-ins/wpg/wpg.c
@@ -322,7 +322,7 @@ begin_render(DiaRenderer *self, const DiaRectangle *update)
   WriteFillAttr(renderer, &color, TRUE);
   WriteFillAttr(renderer, &color, FALSE);
 
-  g_free(pPal);
+  g_clear_pointer (&pPal, g_free);
 }
 
 static void
@@ -515,7 +515,7 @@ draw_polyline(DiaRenderer *self,
 
   fwrite_le(pData, sizeof(gint16), num_points*2, renderer->file);
 
-  g_free(pData);
+  g_clear_pointer (&pData, g_free);
 }
 
 static void
@@ -560,7 +560,7 @@ draw_polygon(DiaRenderer *self,
   /* switch off fill */
   WriteFillAttr(renderer, fill ? fill : stroke, FALSE);
 
-  g_free(pData);
+  g_clear_pointer (&pData, g_free);
 }
 
 static void
@@ -597,7 +597,7 @@ draw_rect(DiaRenderer *self,
     renderer->LineAttr.Type = lt;
   /* switch off fill */
   WriteFillAttr(renderer, fill ? fill : stroke, FALSE);
-  g_free(pData);
+  g_clear_pointer (&pData, g_free);
 }
 
 static void
@@ -774,7 +774,7 @@ draw_bezier(DiaRenderer *self,
   }
 
   fwrite_le (pts, sizeof (gint16), 2 * (numpoints*3-2), renderer->file);
-  g_free (pts);
+  g_clear_pointer (&pts, g_free);
 }
 
 static gpointer parent_class = NULL;
@@ -976,8 +976,8 @@ draw_image(DiaRenderer *self,
     fclose(f);
   }
 #endif
-  g_free(pDiaImg);
-  g_free(pOut);
+  g_clear_pointer (&pDiaImg, g_free);
+  g_clear_pointer (&pOut, g_free);
 }
 
 /* gobject boiler plate */
@@ -1170,7 +1170,7 @@ export_data(DiagramData *data, DiaContext *ctx,
 
   data_render(data, DIA_RENDERER(renderer), NULL, NULL, NULL);
 
-  g_object_unref(renderer);
+  g_clear_object (&renderer);
 
   return TRUE;
 }
diff --git a/plug-ins/xfig/xfig-export.c b/plug-ins/xfig/xfig-export.c
index ca9abce6..69408d3a 100644
--- a/plug-ins/xfig/xfig-export.c
+++ b/plug-ins/xfig/xfig-export.c
@@ -1110,20 +1110,21 @@ draw_string(DiaRenderer *self,
     return;
   }
 
-  figtext = figText(renderer, (unsigned char *) text);
+  figtext = figText (renderer, (unsigned char *) text);
   /* xfig texts are specials */
-  fprintf(renderer->file, "4 %d %d %d 0 %d %s 0.0 6 0.0 0.0 %d %d %s\\001\n",
-         figAlignment(renderer, alignment),
-         figColor(renderer, color),
-         figDepth(renderer),
-         figFont(renderer),
-         xfig_dtostr(d_buf, figFontSize(renderer)),
-         (int)figCoord(renderer, pos->x),
-         (int)figCoord(renderer, pos->y),
-         figtext);
-  g_free(figtext);
+  fprintf (renderer->file, "4 %d %d %d 0 %d %s 0.0 6 0.0 0.0 %d %d %s\\001\n",
+           figAlignment (renderer, alignment),
+           figColor (renderer, color),
+           figDepth (renderer),
+           figFont (renderer),
+           xfig_dtostr (d_buf, figFontSize (renderer)),
+           (int) figCoord (renderer, pos->x),
+           (int) figCoord (renderer, pos->y),
+           figtext);
+  g_clear_pointer (&figtext, g_free);
 }
 
+
 static void
 draw_image(DiaRenderer *self,
            Point *point,
@@ -1150,10 +1151,11 @@ draw_image(DiaRenderer *self,
          (int)figCoord(renderer, point->x), (int)figCoord(renderer, point->y));
 }
 
+
 static void
-draw_object(DiaRenderer *self,
-            DiaObject   *object,
-           DiaMatrix   *matrix)
+draw_object (DiaRenderer *self,
+             DiaObject   *object,
+             DiaMatrix   *matrix)
 {
   XfigRenderer *renderer = XFIG_RENDERER(self);
 
@@ -1164,8 +1166,10 @@ draw_object(DiaRenderer *self,
     fprintf(renderer->file, "6 0 0 0 0\n");
     if (matrix) {
       DiaRenderer *tr = dia_transform_renderer_new (self);
+
       dia_renderer_draw_object (tr, object, matrix);
-      g_object_unref (tr);
+
+      g_clear_object (&tr);
     } else {
       dia_object_draw (object, DIA_RENDERER (renderer));
     }
@@ -1173,6 +1177,7 @@ draw_object(DiaRenderer *self,
   }
 }
 
+
 static gboolean
 export_fig(DiagramData *data, DiaContext *ctx,
           const gchar *filename, const gchar *diafilename,
@@ -1236,7 +1241,7 @@ export_fig(DiagramData *data, DiaContext *ctx,
 
   dia_renderer_end_render (DIA_RENDERER (renderer));
 
-  g_object_unref (renderer);
+  g_clear_object (&renderer);
 
   fclose (file);
 
diff --git a/plug-ins/xfig/xfig-import.c b/plug-ins/xfig/xfig-import.c
index 6a64785d..308ad992 100644
--- a/plug-ins/xfig/xfig-import.c
+++ b/plug-ins/xfig/xfig-import.c
@@ -294,7 +294,7 @@ fig_read_arrow(FILE *file, DiaContext *ctx)
        break;
     default:
        dia_context_add_message(ctx, _("Unknown arrow type %d\n"), arrow_type);
-       g_free(arrow);
+       g_clear_pointer (&arrow, g_free);
        return NULL;
     }
     arrow->width = width/FIG_UNIT;
@@ -343,7 +343,7 @@ fig_fix_text(gchar *text) {
         g_printerr ("Fails to validate %s\n", converted);
         return text;
       }
-      if (text != converted) g_free(text);
+      if (text != converted) g_clear_pointer (&text, g_free);
       return converted;
     } else {
       return text;
@@ -601,9 +601,9 @@ fig_read_polyline(FILE *file, DiaContext *ctx)
  exit:
     setlocale(LC_NUMERIC, old_locale);
     prop_list_free(props);
-    g_free(forward_arrow_info);
-    g_free(backward_arrow_info);
-    g_free(image_file);
+    g_clear_pointer (&forward_arrow_info, g_free);
+    g_clear_pointer (&backward_arrow_info, g_free);
+    g_clear_pointer (&image_file, g_free);
     return newobj;
 }
 
@@ -826,9 +826,9 @@ fig_read_spline(FILE *file, DiaContext *ctx)
  exit:
     setlocale(LC_NUMERIC, old_locale);
     prop_list_free(props);
-    g_free(forward_arrow_info);
-    g_free(backward_arrow_info);
-    g_free(points);
+    g_clear_pointer (&forward_arrow_info, g_free);
+    g_clear_pointer (&backward_arrow_info, g_free);
+    g_clear_pointer (&points, g_free);
     return newobj;
 }
 
@@ -925,8 +925,8 @@ fig_read_arc(FILE *file, DiaContext *ctx)
 
  exit:
     setlocale(LC_NUMERIC, old_locale);
-    g_free(forward_arrow_info);
-    g_free(backward_arrow_info);
+    g_clear_pointer (&forward_arrow_info, g_free);
+    g_clear_pointer (&backward_arrow_info, g_free);
     return newobj;
 }
 
@@ -987,7 +987,7 @@ fig_read_text(FILE *file, DiaContext *ctx)
 
     tprop = g_ptr_array_index(props,0);
     tprop->text_data = g_strdup(text_buf);
-    /*g_free(text_buf); */
+    /*g_clear_pointer (&text_buf, g_free); */
     tprop->attr.alignment = sub_type;
     tprop->attr.position.x = x/FIG_UNIT;
     tprop->attr.position.y = y/FIG_UNIT;
@@ -1017,15 +1017,16 @@ fig_read_text(FILE *file, DiaContext *ctx)
     }
     tprop->attr.height = font_size*2.54/72.0;
     tprop->attr.color = fig_color(color, ctx);
-    newobj->ops->set_props(newobj, props);
+    dia_object_set_properties (newobj, props);
 
     /* Depth field */
     add_at_depth(newobj, depth, ctx);
 
  exit:
-    setlocale(LC_NUMERIC, old_locale);
-    if (text_buf != NULL) g_free(text_buf);
-    if (props != NULL) prop_list_free(props);
+    setlocale (LC_NUMERIC, old_locale);
+    g_clear_pointer (&text_buf, g_free);
+    g_clear_pointer (&props, prop_list_free);
+
     return newobj;
 }
 
diff --git a/plug-ins/xslt/xslt.c b/plug-ins/xslt/xslt.c
index 574695de..0621487b 100644
--- a/plug-ins/xslt/xslt.c
+++ b/plug-ins/xslt/xslt.c
@@ -62,12 +62,10 @@ export_xslt (DiagramData *data,
              const gchar *diaf,
              void        *user_data)
 {
-  if (filename != NULL)
-    g_free (filename);
+  g_clear_pointer (&filename, g_free);
 
   filename = g_strdup (f);
-  if (diafilename != NULL)
-    g_free (diafilename);
+  g_clear_pointer (&diafilename, g_free);
 
   diafilename = g_strdup (diaf);
 
@@ -89,11 +87,11 @@ xslt_ok (void)
   xmlErrorPtr error_xml = NULL;
   gchar *directory = g_path_get_dirname (filename);
   gchar *uri = g_filename_to_uri (directory, NULL, NULL);
-  g_free (directory);
+  g_clear_pointer (&directory, g_free);
 
   /* strange: requires an uri, but the last char is platform specifc?! */
   params[1] = g_strconcat ("'", uri, G_DIR_SEPARATOR_S, "'", NULL);
-  g_free (uri);
+  g_clear_pointer (&uri, g_free);
 
   file = g_fopen (diafilename, "r");
 
@@ -206,7 +204,7 @@ read_implementations (xmlNodePtr cur, gchar *path)
       if (to->xsl) {
         xmlFree(to->xsl);
       }
-      g_free(to);
+      g_clear_pointer (&to, g_free);
       to = NULL;
     } else {
       if (first == NULL) {
@@ -272,8 +270,7 @@ read_configuration(const char *config)
 
       if (!(new_from->name && new_from->xsl)) {
         g_warning ("'name' and 'stylesheet' attributes are required for the language element %s in XSLT 
plugin configuration file", cur->name);
-        g_free (new_from);
-        new_from = NULL;
+        g_clear_pointer (&new_from, g_free);
       } else {
         /* make filename absolute */
         {
@@ -299,7 +296,7 @@ read_configuration(const char *config)
     g_warning ("No stylesheets configured in %s for XSLT plugin", config);
   }
 
-  g_free (path);
+  g_clear_pointer (&path, g_free);
   xmlFreeDoc (doc);
   xmlCleanupParser ();
 
@@ -342,11 +339,11 @@ dia_plugin_init (PluginInfo *info)
   }
 
   global_res = read_configuration (path);
-  g_free (path);
+  g_clear_pointer (&path, g_free);
 
   path = dia_config_filename ("xslt" G_DIR_SEPARATOR_S "stylesheets.xml");
   user_res = read_configuration(path);
-  g_free (path);
+  g_clear_pointer (&path, g_free);
 
   if (global_res == DIA_PLUGIN_INIT_OK || user_res == DIA_PLUGIN_INIT_OK) {
     xsl_from = g_ptr_array_index (froms, 0);
diff --git a/tests/test-boundingbox.c b/tests/test-boundingbox.c
index e8331c4a..26cf2605 100644
--- a/tests/test-boundingbox.c
+++ b/tests/test-boundingbox.c
@@ -141,19 +141,20 @@ _check_one_bezier (gconstpointer p)
   polybezier_bbox (test->pts, test->num, &extra, FALSE, &rect);
   g_assert (rectangle_in_rectangle (&test->box, &rect));
 }
+
+
 static void
 _add_bezier_tests (void)
 {
-  int i, num = sizeof(_test_beziers)/sizeof(struct _TestBeziers);
+  int i, num = sizeof (_test_beziers) / sizeof (struct _TestBeziers);
 
-  for (i = 0; i < num; ++i)
-    {
-      gchar *testpath = g_strdup_printf ("/Dia/BoundingBox/Bezier%d", i+1);
+  for (i = 0; i < num; ++i) {
+    char *testpath = g_strdup_printf ("/Dia/BoundingBox/Bezier%d", i+1);
 
-      g_test_add_data_func (testpath, &_test_beziers[i], _check_one_bezier);
+    g_test_add_data_func (testpath, &_test_beziers[i], _check_one_bezier);
 
-      g_free (testpath);
-    }
+    g_clear_pointer (&testpath, g_free);
+  }
 }
 
 #ifdef G_OS_WIN32
diff --git a/tests/test-objects.c b/tests/test-objects.c
index 7c2254f6..b0790ae8 100644
--- a/tests/test-objects.c
+++ b/tests/test-objects.c
@@ -136,7 +136,7 @@ _test_creation (gconstpointer user_data)
 
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 
 static void
@@ -185,9 +185,9 @@ _test_copy (gconstpointer user_data)
 
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
   oc->ops->destroy (oc);
-  g_free (oc);
+  g_clear_pointer (&oc, g_free);
 }
 
 /* small helper to just throw it away */
@@ -197,7 +197,7 @@ _object_change_free(ObjectChange *change)
   if (change) { /* usually this is NULL for move */
     if (change->free) {
       change->free(change);
-      g_free(change);
+      g_clear_pointer (&change, g_free);
     }
   }
 }
@@ -290,7 +290,7 @@ _test_movement (gconstpointer user_data)
     }
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 
 static void
@@ -321,7 +321,7 @@ _test_change (gconstpointer user_data)
   }
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 static void
 _test_move_handle (gconstpointer user_data)
@@ -434,10 +434,10 @@ _test_move_handle (gconstpointer user_data)
     }
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
   if (o2) {
     o2->ops->destroy (o2);
-    g_free (o2);
+    g_clear_pointer (&o2, g_free);
   }
 }
 static void
@@ -589,7 +589,7 @@ _test_connectionpoint_consistency (gconstpointer user_data)
   }
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 static void
 _test_object_menu (gconstpointer user_data)
@@ -657,7 +657,7 @@ _test_object_menu (gconstpointer user_data)
   }
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 
 static void
@@ -789,7 +789,7 @@ _test_draw (gconstpointer user_data)
        }
       /* destroy path object */
       p->ops->destroy (p);
-      g_free (p);
+      g_clear_pointer (&p, g_free);
     }
   else
     {
@@ -797,7 +797,7 @@ _test_draw (gconstpointer user_data)
     }
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 
 static void
@@ -842,7 +842,7 @@ _test_distance_from (gconstpointer user_data)
 
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 
 #include "lib/prop_geomtypes.h" /* BezPointarrayProperty */
@@ -997,7 +997,7 @@ _test_segments (gconstpointer user_data)
     prop->ops->free (prop);
   /* finally */
   o->ops->destroy (o);
-  g_free (o);
+  g_clear_pointer (&o, g_free);
 }
 /*
  * A dictionary interface to all registered object(-types)
@@ -1014,43 +1014,43 @@ _ot_item (gpointer key,
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "Creation");
   g_test_add_data_func (testpath, type, _test_creation);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "Copy");
   g_test_add_data_func (testpath, type, _test_copy);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "Movement");
   g_test_add_data_func (testpath, type, _test_movement);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "Change");
   g_test_add_data_func (testpath, type, _test_change);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "MoveHandle");
   g_test_add_data_func (testpath, type, _test_move_handle);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "ConnectionPoints");
   g_test_add_data_func (testpath, type, _test_connectionpoint_consistency);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "ObjectMenu");
   g_test_add_data_func (testpath, type, _test_object_menu);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "Draw");
   g_test_add_data_func (testpath, type, _test_draw);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "DistanceFrom");
   g_test_add_data_func (testpath, type, _test_distance_from);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   testpath = g_strdup_printf ("%s/%s/%s", base, name, "Segments");
   g_test_add_data_func (testpath, type, _test_segments);
-  g_free (testpath);
+  g_clear_pointer (&testpath, g_free);
 
   ++num_objects;
 }
diff --git a/tests/test-svg.c b/tests/test-svg.c
index 290cba42..563e803d 100644
--- a/tests/test-svg.c
+++ b/tests/test-svg.c
@@ -106,25 +106,28 @@ _check_one_path (gconstpointer _p)
 
   g_array_free (points, TRUE);
 }
+
+
 static void
 _add_path_tests (void)
 {
-  int i, num = sizeof(_test_path)/sizeof(PathData);
-  
-  for (i = 0; i < num; ++i)
-    {
-      gchar *testpath = g_strdup_printf ("/Dia/svg/test-path%d", i);
+  int i, num = sizeof (_test_path) / sizeof (PathData);
 
-      g_test_add_data_func (testpath, &_test_path[i], _check_one_path);
+  for (i = 0; i < num; ++i) {
+    char *testpath = g_strdup_printf ("/Dia/svg/test-path%d", i);
 
-      g_free (testpath);
-    }
+    g_test_add_data_func (testpath, &_test_path[i], _check_one_path);
+
+    g_clear_pointer (&testpath, g_free);
+  }
 }
+
+
 int
 main (int argc, char** argv)
 {
   int ret;
-  
+
   g_test_init (&argc, &argv, NULL);
 
   libdia_init (DIA_MESSAGE_STDERR);


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