为什么 yyparse() 会导致我的程序崩溃?
Why does yyparse() causes my program to crash?
我正在制作一个汇编程序。我正在使用 bison 和 flex 来这样做。
我还有一个 C 文件,其中有我的主要功能。但是由于某些原因调用 yyparse() 函数后程序崩溃了。
这是我的代码示例。但是结果一样。
我的 lexer.l (lex) 文件
%{
#include <stdio.h>
#include "y.tab.h"
%}
%option nounput yylineno
%%
"sub" return SUB;
";" return SEMICOLON;
. ;
[ \t]+ ;
%%
int yywrap()
{
return 0;
}
我的 grammar.y (yacc) 文件。
%{
#include <stdio.h>
#include <string.h>
void yyerror(const char *str)
{
fprintf(stderr,"error: %s\n",str);
}
%}
%token SUB SEMICOLON
%%
commands: /* empty */
| commands command
;
command:
sub
;
sub:
SUB SEMICOLON
{
printf("\tSub Detected\n");
}
;
%%
我的 main.c 文件。
#include <stdio.h>
extern int yyparse();
extern yy_scan_bytes ( const char *, int);
//My input buffer
char * memblock = "sub;\n";
int main()
{
yy_scan_bytes(memblock, strlen(memblock));
yyparse();
return 0;
}
最后我是如何编译它的。
bison -y -d grammar.y
flex lexer.l
gcc y.tab.c lex.yy.c -c
gcc main.c y.tab.o lex.yy.o
这是结果。
Sub Detected
Segmentation fault
我想知道如何修复 Segmentation fault
错误。谢谢。
问题是你的 yywrap 函数是 returning 0(false == 还没有结束,需要读取更多输入),但没有设置输入,所以当扫描仪尝试要读取更多数据,它会崩溃。
yywrap return 1 (true) 你会得到一个 EOF,yyparser 会 return 一切都会好起来的。
或者,使用 %option noyywrap
并删除它。
我正在制作一个汇编程序。我正在使用 bison 和 flex 来这样做。 我还有一个 C 文件,其中有我的主要功能。但是由于某些原因调用 yyparse() 函数后程序崩溃了。
这是我的代码示例。但是结果一样。
我的 lexer.l (lex) 文件
%{
#include <stdio.h>
#include "y.tab.h"
%}
%option nounput yylineno
%%
"sub" return SUB;
";" return SEMICOLON;
. ;
[ \t]+ ;
%%
int yywrap()
{
return 0;
}
我的 grammar.y (yacc) 文件。
%{
#include <stdio.h>
#include <string.h>
void yyerror(const char *str)
{
fprintf(stderr,"error: %s\n",str);
}
%}
%token SUB SEMICOLON
%%
commands: /* empty */
| commands command
;
command:
sub
;
sub:
SUB SEMICOLON
{
printf("\tSub Detected\n");
}
;
%%
我的 main.c 文件。
#include <stdio.h>
extern int yyparse();
extern yy_scan_bytes ( const char *, int);
//My input buffer
char * memblock = "sub;\n";
int main()
{
yy_scan_bytes(memblock, strlen(memblock));
yyparse();
return 0;
}
最后我是如何编译它的。
bison -y -d grammar.y
flex lexer.l
gcc y.tab.c lex.yy.c -c
gcc main.c y.tab.o lex.yy.o
这是结果。
Sub Detected
Segmentation fault
我想知道如何修复 Segmentation fault
错误。谢谢。
问题是你的 yywrap 函数是 returning 0(false == 还没有结束,需要读取更多输入),但没有设置输入,所以当扫描仪尝试要读取更多数据,它会崩溃。
yywrap return 1 (true) 你会得到一个 EOF,yyparser 会 return 一切都会好起来的。
或者,使用 %option noyywrap
并删除它。