繁体   English   中英

为什么yyparse()导致我的程序崩溃?

[英]Why does yyparse() causes my program to crash?

我正在制作一个汇编程序。 我使用野牛和屈曲这样做。 我也有一个C文件,其中有我的主要功能。 但是由于某种原因,在yyparse()函数被称为progam崩溃之后。

这是我的代码的示例。 但是,结果是一样的。

我的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函数返回0(false ==尚未包装,需要读取更多输入),但未设置输入,因此,当扫描程序尝试读取更多数据时,它将崩溃。

让yywrap返回1(true),您将得到EOF,而yyparser将返回,一切都会很好。

或者,使用%option noyywrap并摆脱它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM