A part of my bison grammar is as shown
head: OPEN statement CLOSE
{
$$=$2;
}
;
statement: word
{
$$=$1;
}
| statement word
{
$$=$1;
printf("%s",$$);
}
;
Now if my input is [hai hello] where [ is the OPEN & ] is the CLOSE respectively,then in the printf statement I get the output as "hai hello" itself..but in the $$ of head I get "hai hello]". Same happens with other grammars too.i.e., if i try to print valye of $1,the values of $2,$3,... are also printed.. why is it so.
The problem is probably in your lexer -- you probably have lexer actions that do something like yylval.str = yytext;
to return a semantic value. The problem is that yytext
is a pointer into the scanner's read buffer and is only valid until the next call to yylex
. So all your semantic values in the parser quickly become dangling pointers and what they point at is no longer valid.
You need to make a copy of the token string in the lexer. Use an action something like
yylval.str = strdup(yytext);
. Of course, then you have potential memory leak issues in your parser -- you need to free
the $n values you don't need anymore.