如果文件不存在,Flex Bison 从文件中读取会出现分段错误

Flex Bison Reading from file get segmentation fault if file does not exist

我有可以解析文件内容的 flex 代码,但是如果尝试读取的文件不存在,我会遇到分段错误。

flex 文件也与 bison 接口,但这部分代码没有,如果您仍然想要 bison 文件,请告诉我。

灵活代码:

%{
#include <stdlib.h>
#include "helper.h"
#include "spire.tab.h"
void yyerror(char *);
%}

%x incl
%%
include BEGIN(incl);

...

\"[a-zA-Z0-9_ ]+\.(spr)\" {
        char *f = strdup(yytext);

        f++[strlen(f)-1] = 0;

        yyin = fopen( f, "r" );

        if (! yyin)
                printf("Could not read %s\n", f);
        yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));

        BEGIN(INITIAL);
}

<<EOF>> {
        yypop_buffer_state();

        if ( !YY_CURRENT_BUFFER )
        {
                yyterminate();
        }
}


[ \t\n]+ ; /* ignore whitespace */
. yyerror("Unknown character");


%%

int yywrap(void) {
 return 1;
}

如果文件不存在,我得到这个用于输出(对于文件 fle.spr)

Could not read fle.spr
Segmentation fault (core dumped)

编辑:

已更改

 if (! yyin)
     printf("Could not read %s\n", f);
 yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));

if (! yyin){
    printf("Could not read %s\n", f);
}else{
    yypush_buffer_state(yy_create_buffer( yyin, YY_BUF_SIZE ));
}

仍然出现同样的错误

我不确定为什么会这样。

您的代码检查打开的文件是否有效。如果不是,它会打印一条错误消息(在 stdout 而不是 stderr,但这是一个次要的细节) 然后继续

紧接着,扫描器将尝试从 yyin 读取,但 yyin 为 NULL。正如预期的那样,它会出现段错误。

如果文件不存在,不要尝试读取它。就这么简单。