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. But by some reason after the yyparse() function is called the progam crashes.
This is an example of my code. But it has the same outcome.
My lexer.l (lex) file
%{
#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.
%{
#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.
#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. 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.
Have yywrap return 1 (true) and you'll get an EOF and yyparser will return and all will be good.
Alternately, use %option noyywrap
and get rid of it.