0

I'm including files within the scope of my lex grammar, and looking at the example code taken from the flex manual, I wondered if the file handles being consumed were not being released.

I drilled through the generated code starting at yypop_buffer_state() and concluded the file handles aren't being closed/released.

Could someone confirm this? Is the example code wrong?

 /* the "incl" state is used for picking up the name
  * of an include file
  */
 %x incl
 %%
 include             BEGIN(incl);

 [a-z]+              ECHO;
 [^a-z\n]*\n?        ECHO;

 <incl>[ \t]*      /* eat the whitespace */
 <incl>[^ \t\n]+   { /* got the include file name */
                     yyin = fopen( yytext, "r" );

                     if ( ! yyin )
                         error( ... );

                     yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));

                     BEGIN(INITIAL);
                   }
<<EOF>>            {
                     yypop_buffer_state();
                     if ( !YY_CURRENT_BUFFER ) {
                         yyterminate();
                     }
                   }
rici
  • 234,347
  • 28
  • 237
  • 341
Jamie
  • 7,075
  • 12
  • 56
  • 86

1 Answers1

0

yes, this will leak file handles, you have to call fclose before yypop_buffer_state(), there is an example in the tests and code around that is informative about this.

{
    if (yyin && yyin != stdin) {
        fclose(yyin);
    }
    yypop_buffer_state();
    if ( !YY_CURRENT_BUFFER ) {
        yyterminate();
    }
}
DRC
  • 4,898
  • 2
  • 21
  • 35
  • Obviously, yes I could. The question is "Do I have to?" (or "Is the example at the link misleading?") – Jamie Dec 16 '14 at 19:37
  • 1
    @Jamie yes you have to, the [test here is more informative](http://sourceforge.net/p/flex/flex/ci/7b7d125b117f520b033de65b597e80c21abc3be5/tree/tests/test-include-by-push/scanner.l#), or you can find [different examples](https://gitlab.labs.nic.cz/labs/knot/blob/master/src/knot/conf/cf-lex.l) around. – DRC Dec 16 '14 at 23:02