title: freeing the string allocated in strdup() from flex/bison
body: <p>I have flex code that copies a string lexeme using <code>strdup()</code>. </p>
  
  <pre><code>%{   
  #include "json.tab.h"
  #define YY_DECL extern "C" int yylex()
  
  %}
  %option noyywrap
  
  %%
  
  [ \t\n]+ ; 
  \"[a-zA-Z]+\" {yylval.sval = strdup(yytext); return STRING; }
  [0-9]+ {yylval.ival = atoi(yytext); return NUMBER; }
  . {return yytext[0];} ; 
  
  %%
  </code></pre>
  
  <p><code>strdup()</code> allocates memory and copies the input string into it and return (<a href="https://stackoverflow.com/questions/252782/strdup-what-does-it-do-in-c">strdup() - what does it do in C?</a>), so I guess I need to free it up when I don't need it anymore. </p>
  
  <p>From this post:<a href="https://stackoverflow.com/questions/6401286/when-is-destructor-invoked-in-bison">When is %destructor invoked in BISON?</a>, I added <code>%destructor { free($$); printf("free");} STRING</code> in the yacc file.</p>
  
  <p>However, I don't see the <code>free()</code> is invoked even when <code>yylval.sval</code> is assigned with new string returned from <code>strdup()</code>. </p>
  
  <p>What might be wrong? How to free the allocated string in flex/bison?</p>
  
  <h2>Added</h2>
  
  <p>I think about using statically allocated sval as follows:</p>
  
  <pre><code>%union {
      int ival;
      char sval[100]; // char* sval;
  }
  </code></pre>
  
  <p>The flex code now becomes (without the checking code if yytext is less than 100 bytes):</p>
  
  <pre><code>\"[a-zA-Z]+\" {
      //yylval.sval = strdup(yytext);
      memset(yylval.sval, 0, 100);
      strcpy(yylval.sval, yytext);
      return STRING; 
  }
  </code></pre>
  
  <p>I'm not sure if this approach is what people normally use. </p>
  
  <h2>Added2</h2>
  
  <p>For my application, simple interning is OK. </p>
  
  <pre><code>extern char buffer[]; // [100];
  %}
  %option noyywrap
  
  %%
  
  \"[a-zA-Z]+\" {
          //yylval.sval = strdup(yytext);
          memset(buffer, 0, 100);
          strcpy(buffer, yytext);
          yylval.sval = buffer;
          return STRING; 
      }
  ...
  
  char buffer[100];
  </code></pre>
  
  <p>For yacc code</p>
  
  <pre><code>%union {
      int ival;
      char *sval; 
  }
  </code></pre>