jplevyak / dparser

A Scannerless GLR parser/parser generater.
https://github.com/jplevyak/dparser
BSD 3-Clause "New" or "Revised" License
105 stars 14 forks source link

Errors reported by valgrind #34

Open mingodad opened 1 year ago

mingodad commented 1 year ago

Some easy to fix memory issues reported by valgrind:

diff --git a/gram.c b/gram.c
index 4ef933b..0e7ecd0 100644
--- a/gram.c
+++ b/gram.c
@@ -1431,7 +1431,9 @@ static void print_term_escaped(Term *t, int double_escaped) {
     if (!t->string || !*t->string)
       printf("<EOF> ");
     else {
-      printf("'%s' ", double_escaped ? escape_string_single_quote(s) : s);
+      char *ds = double_escaped ? escape_string_single_quote(s) : s;
+      printf("'%s' ", ds);
+      if(ds != s) FREE(ds);
       if (t->ignore_case) printf("/i ");
       if (t->term_priority) printf("%sterm %d ", double_escaped ? "#" : "$", t->term_priority);
     }
@@ -1439,7 +1441,9 @@ static void print_term_escaped(Term *t, int double_escaped) {
     char *quote = double_escaped ? "\\\"" : "\"";
     s = t->string ? escape_string(t->string) : NULL;
     /* char *s = t->string; // ? escape_string(t->string) : NULL; */
-    printf("%s%s%s ", quote, double_escaped ? escape_string(s) : s, quote);
+    char *ds = double_escaped ? escape_string(s) : s;
+    printf("%s%s%s ", quote, ds, quote);
+    if(ds != s) FREE(ds);
     if (t->ignore_case) printf("/i ");
     if (t->term_priority) printf("%sterm %d ", double_escaped ? "#" : "$", t->term_priority);
   } else if (t->kind == TERM_CODE) {
@@ -1450,7 +1454,7 @@ static void print_term_escaped(Term *t, int double_escaped) {
     printf("%s ", s);
   } else
     d_fail("unknown token kind");
-  if (s) FREE(s);
+  if (s != t->string) FREE(s);
 }

 /* print_elem changed to call print_term_escaped */
@@ -1594,7 +1598,7 @@ static void print_declarations(Grammar *g) {
 }

 void print_rdebug_grammar(Grammar *g, char *pathname) {
-  char ver[30];
+  char ver[128]; /* the old size was too short */
   d_version(ver);

   printf("/*\n  Generated by Make DParser Version %s\n", ver);
mingodad commented 1 year ago

Also when trying to compile ansic.g:

gcc -I.. -c ansic.g.d_parser.c 
ansic.g: In function ‘d_speculative_reduction_code_98_242_gram’:
ansic.g:200:49: error: ‘D_ParseNode’ {aka ‘struct D_ParseNode’} has no member named ‘start’
  200 |   if (is_one_of($n0.start, $n0.end, reserved_words))
      |                                                 ^