views:

63

answers:

1

I have a flex bison application. For a few of my tokens, I copy out the yytext from flex using strdup. This works great except when there is an error of an unexpected token.

simple example

flex.l:
...
[a-zA-Z0-9]+ { lval.string = strdup(yytext); return IDENT };
[\{\}]       { return yytext[0] };
...

and

parse.y
...
%destructor { free($$); } IDENT
%destructor { free($$->name); free($$->type); free($$); } tag
...
tag: IDENT '{' IDENT '}'
     {
         struct tag *mytag = malloc(sizeof(struct tag));
         mytag->name = $1;
         mytag->type = $3;
         $<tag>$ = mytag;
      }
...

Now suppose I hand it the input:

blah blah blah

The lexer will send up the first IDENT token, which gets pushed onto the stack. After the first token it's expecting a bracket token, but instead gets another IDENT token. This is a syntax error. The destructor will be called on the first IDENT token, but not on the second one (the unexpected one). I haven't been able to find a way to destruct the unexpected token. Does anyone know how I should do it?

A: 

I found that appropriate use of the 'error' token in flex prompts it to correctly call the destructor function. Go me!

parse.y
...
%destructor { free($$); } IDENT
%destructor { free($$->name); free($$->type); free($$); } tag
...
tags: tag tags | error tags | ;

tag: IDENT '{' IDENT '}'
     {
         struct tag *mytag = malloc(sizeof(struct tag));
         mytag->name = $1;
         mytag->type = $3;
         $<tag>$ = mytag;
     }
...
jdizzle