0

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.

Jackzz
  • 1,417
  • 4
  • 24
  • 53

1 Answers1

0

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.

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226
  • Is there really any problem if we don't fix the shift/reduce conflicts in the grammar? – Jackzz Aug 14 '14 at 04:34
  • @ANU: I don't understand your question -- there are no conflicts in the grammar you posted, and even if there were, that's completely independent of the issue of correctly allocating semantic values so as to avoid dangling pointers. – Chris Dodd Aug 14 '14 at 05:20
  • @ANU: then you should ask another question. Generally, a conflict in the grammar means that bison builds a parser that parses a subset of the language. That may be ok, or may be a problem -- you need to understand the specific conflict occurring and the result of the default resolution of the conflict. – Chris Dodd Aug 14 '14 at 05:48
  • kk. Thank you. I have posted another question for my doubt. Hope you will help me in solving that too. – Jackzz Aug 14 '14 at 06:38