Browse Source

Avoid mem leaks on parse fail.

Stefano Cossu 4 years ago
parent
commit
7452a73e6a
2 changed files with 22 additions and 16 deletions
  1. 21 15
      src/codec/nt_lexer.re
  2. 1 1
      test/test_codec_nt.c

+ 21 - 15
src/codec/nt_lexer.re

@@ -334,15 +334,24 @@ LSUP_nt_parse_doc (FILE *stream, LSUP_Graph **gr_p, size_t *ct, char **err_p)
 
     void *parser = ParseAlloc (malloc);
 
+    LSUP_rc rc;
+
     LSUP_Graph *gr = LSUP_graph_new (LSUP_STORE_MEM);
+    if (UNLIKELY (!gr)) return LSUP_MEM_ERR;
+
     LSUP_GraphIterator *it = LSUP_graph_add_init (gr);
+    if (UNLIKELY (!it)) {
+        LSUP_graph_free (gr);
+        return LSUP_MEM_ERR;
+    }
+
     LSUP_Term *term = NULL;
 
     for (;;) {
         int ttype = lex (&parse_it, &term);
 
         if (ttype == -1) {
-            char token[16];
+            char token[16] = {'\0'};
             strncpy (token, (const char *)parse_it.tok, 15);
 
             char *err_start = "Parse error near token `";
@@ -352,14 +361,14 @@ LSUP_nt_parse_doc (FILE *stream, LSUP_Graph **gr_p, size_t *ct, char **err_p)
                     err_info, "[...]' at line %u, character %ld.\n",
                     parse_it.line, parse_it.cur - parse_it.bol);
 
-            size_t err_size = strlen (err_start) + strlen (token)
-                    + strlen (err_info) + 1;
+            size_t err_size = strlen (err_start) + 16 + strlen(err_info);
             char *err_str = malloc (err_size);
             sprintf (err_str, "%s%s%s", err_start, token, err_info);
 
+            rc = LSUP_VALUE_ERR;
             *err_p = err_str;
 
-            goto fail;
+            goto finally;
         }
 
         Parse (parser, ttype, term, it);
@@ -367,27 +376,24 @@ LSUP_nt_parse_doc (FILE *stream, LSUP_Graph **gr_p, size_t *ct, char **err_p)
         if (ttype == T_EOF) break;
     };
 
-    Parse (parser, 0, NULL, it);
-
-    LSUP_graph_add_done (it);
-
     if (ct) *ct = parse_it.ct;
 
     TRACE ("Parsed %u triples.\n", parse_it.ct);
     TRACE ("Graph size: %lu\n", LSUP_graph_size (gr));
 
-    LSUP_term_free (term);
+    rc = parse_it.ct > 0 ? LSUP_OK : LSUP_NORESULT;
+    *gr_p = gr;
 
+finally:
+    Parse (parser, 0, NULL, it);
     ParseFree (parser, free);
     parse_done (&parse_it);
 
-    *gr_p = gr;
-
-    return LSUP_OK;
+    LSUP_graph_add_done (it);
+    LSUP_term_free (term);
 
-fail:
-    LSUP_graph_free (gr);
+    if (rc < 0) LSUP_graph_free (gr);
 
-    return LSUP_VALUE_ERR;
+    return rc;
 }
 

+ 1 - 1
test/test_codec_nt.c

@@ -241,8 +241,8 @@ test_decode_nt_bad_graph()
     ASSERT (strstr (err, "line 3") != NULL, "Wrong error line report!");
     ASSERT (strstr (err, "character 16") != NULL, "Wrong error char report!");
 
+    free (err);
     fclose (input);
-
     LSUP_graph_free (gr);
 
     return 0;