0
votes

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();
                     }
                   }
1

1 Answers

0
votes

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();
    }
}