[librest/librest-0-7] xml-node: Use GString in rest_xml_node_print()



commit a09ea6bd74d6234be8456e7039403bc1c1d078bd
Author: Christophe Fergeau <cfergeau redhat com>
Date:   Mon Jun 20 12:05:48 2016 +0200

    xml-node: Use GString in rest_xml_node_print()
    
    The current code is using xml = g_strconcat (xml, ...) which is causing
    some leaks as g_strconcat returns a newly allocated string. Using
    GString avoids this issue without constantly freeing the intermediate
    strings.
    
    This fixes multiple leaks like:
    
    ==16611== 18 bytes in 1 blocks are definitely lost in loss record 124 of 301
    ==16611==    at 0x4C2BBAD: malloc (vg_replace_malloc.c:299)
    ==16611==    by 0x5F5CE58: g_malloc (gmem.c:94)
    ==16611==    by 0x5F75B8E: g_strconcat (gstrfuncs.c:585)
    ==16611==    by 0x4E450CF: rest_xml_node_print (rest-xml-node.c:287)
    ==16611==    by 0x4E451DA: rest_xml_node_print (rest-xml-node.c:305)
    ==16611==    by 0x4E450F8: rest_xml_node_print (rest-xml-node.c:292)
    ==16611==    by 0x4009A0: main (xml.c:40)

 rest/rest-xml-node.c |   21 ++++++++++++---------
 1 files changed, 12 insertions(+), 9 deletions(-)
---
diff --git a/rest/rest-xml-node.c b/rest/rest-xml-node.c
index 57a9426..a8156db 100644
--- a/rest/rest-xml-node.c
+++ b/rest/rest-xml-node.c
@@ -283,38 +283,41 @@ rest_xml_node_print (RestXmlNode *node)
 {
   GHashTableIter iter;
   gpointer       key, value;
-  char          *xml = g_strconcat ("<", node->name, NULL);
+  GString        *xml = g_string_new (NULL);
   RestXmlNode   *n;
 
+  g_string_append (xml, "<");
+  g_string_append (xml, node->name);
+
   g_hash_table_iter_init (&iter, node->attrs);
   while (g_hash_table_iter_next (&iter, &key, &value))
-    xml = g_strconcat (xml, " ", key, "=\'", value, "\'", NULL);
+    g_string_append_printf (xml, " %s =\'%s\'", (char *)key, (char *)value);
 
-  xml = g_strconcat (xml, ">", NULL);
+  g_string_append (xml, ">");
 
   g_hash_table_iter_init (&iter, node->children);
   while (g_hash_table_iter_next (&iter, &key, &value))
     {
       char *child = rest_xml_node_print ((RestXmlNode *) value);
 
-      xml = g_strconcat (xml, child, NULL);
+      g_string_append (xml, child);
       g_free (child);
     }
 
   if (node->content)
-    xml = g_strconcat (xml, node->content, "</", node->name, ">", NULL);
-  else
-    xml = g_strconcat (xml, "</", node->name, ">", NULL);
+    g_string_append (xml, node->content);
+
+  g_string_append_printf (xml, "</%s>", node->name);
 
   for (n = node->next; n; n = n->next)
     {
       char *sibling = rest_xml_node_print (n);
 
-      xml = g_strconcat (xml, sibling, NULL);
+      g_string_append (xml, sibling);
       g_free (sibling);
     }
 
-  return xml;
+  return g_string_free (xml, FALSE);
 }
 
 /**


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