简体   繁体   English

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

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

im making an assembler. 我正在制作一个汇编程序。 Im using bison and flex to do so. 我使用野牛和屈曲这样做。 I Also have a C file in which I have my main function. 我也有一个C文件,其中有我的主要功能。 But by some reason after the yyparse() function is called the progam crashes. 但是由于某种原因,在yyparse()函数被称为progam崩溃之后。

This is an example of my code. 这是我的代码的示例。 But it has the same outcome. 但是,结果是一样的。

My lexer.l (lex) file 我的lexer.l(lex)文件

%{
#include <stdio.h>
#include "y.tab.h"
%}
%option nounput yylineno
%%
"sub"               return SUB;
";"                 return SEMICOLON;
.                   ;
[ \t]+              ;
%%
int yywrap()
{
    return 0;
}

My grammar.y (yacc) file. 我的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");
    }
    ;
%%

My main.c file. 我的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;
}

Finally how I compile it. 最后,我如何编译它。

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

This is the outcome. 这就是结果。

    Sub Detected

Segmentation fault

I would like to know how to fix the Segmentation fault error. 我想知道如何解决Segmentation fault错误。 Thanks. 谢谢。

The problem is that your yywrap function is returning 0 (false == not yet wrapped up, more input needs to be read), but is not setting up the input, so when the scanner tries to read more data, it crashes. 问题在于您的yywrap函数返回0(false ==尚未包装,需要读取更多输入),但未设置输入,因此,当扫描程序尝试读取更多数据时,它将崩溃。

Have yywrap return 1 (true) and you'll get an EOF and yyparser will return and all will be good. 让yywrap返回1(true),您将得到EOF,而yyparser将返回,一切都会很好。

Alternately, use %option noyywrap and get rid of it. 或者,使用%option noyywrap并摆脱它。

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

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