gumbo-libxml icon indicating copy to clipboard operation
gumbo-libxml copied to clipboard

Double free in example program

Open runekl opened this issue 8 years ago • 0 comments

Suggest the following patch for example program to avoid reading outside buffer and freeing nodes twice and a memory leak.

*** example.c	2017-04-30 09:27:06.878903562 +0200
--- example.c	2017-04-30 14:16:04.562413166 +0200
***************
*** 33,38 ****
--- 33,39 ----
    while ((bytes_read = fread(*output + start, 1, *length - start, fp))) {
      start += bytes_read;
    }
+   (*output)[*length] = '\0';
  }
  
  static void delete_nodes(xmlDocPtr doc, const char* xpath_expr) {
***************
*** 57,62 ****
--- 58,65 ----
    // http://www.xmlsoft.org/examples/xpath2.c
    for (int i = xpath_obj->nodesetval->nodeNr - 1; i >= 0; i--) {
      xmlNodePtr node = xpath_obj->nodesetval->nodeTab[i];
+     if (node->type != XML_NAMESPACE_DECL)
+       xpath_obj->nodesetval->nodeTab[i] = NULL;
      xmlUnlinkNode(node);
      xmlFreeNode(node);
    }
***************
*** 82,87 ****
--- 85,91 ----
    int input_length;
    read_file(fp, &input, &input_length);
    xmlDocPtr doc = gumbo_libxml_parse(input);
+   free(input);
    delete_nodes(doc, "//script");
    delete_nodes(doc, "//style");
    delete_nodes(doc, "//link[@rel='stylesheet']");

runekl avatar Apr 30 '17 12:04 runekl