use yytext in bison code

3.5k views Asked by At

When I trying to compile my code in yacc&lex I get this error: this error

yacc Code:

%{
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define YYSTYPE struct node*
typedef struct node{
    char *token;
    struct node *left;
    struct node *right;
} node;
node* mknode(char* token, node *left, node *right);
void Printtree(node *tree);
int yyerror();
%}
%token NUM PLUS MINUS
%left PLUS MINUS
%%
S:exp {printf("OK\n"); Printtree($1);};
exp:exp PLUS exp {$$=mknode("+",$1,$3);}
    | exp MINUS exp{$$=mknode("-",$1,$3);}
    | NUM {$$=mknode(yytext, NULL, NULL);};
%%
#include "lex.yy.c"
int main(){
    return yyparse();
}
node *mknode (char *token, node *left, node *right){
    node *newnode = (node*)malloc(sizeof(node));
    char *newstr = (char*)malloc(sizeof(token)+1);
    strcpy (newstr, token);
    newnode->left=left;
    newnode->right=right;
    newnode->token=newstr;
    return newnode;
}
void Printtree(node* tree){
    printf("%s\n", tree->token);
    if (tree->left)
        Printtree(tree->left);
    if (tree->right)
        Printtree(tree->right);
}
int yyerror(){
    printf("ERROR\n");
    return 0;
}

and the lex Code

%%
[0-9]+ return NUM;
\+ return PLUS;
\- return MINUS;
%%

when i trying to change the yytext to $1 is compiled but when i run the code and type for example 5+6 is saying: (segmentation fault (core dumped))

using ubuntu 64:

lex compile with flex version lex 2.6.0:

lex subProject.lex

and yacc compile with bison version bison(GNU Bison) 3.0.4:

yacc subProject.yacc

and the error maker:

cc subProject -o y.tab.c -ll -Ly
1

There are 1 answers

3
user207421 On BEST ANSWER

You should not use yytext in grammar rules at all. It won't always have the value you think it might have. You should save it in the yyunion in the scanner:

[0-9]+ { yylval.text = strdup(yytext); return NUM; }

and similarly for the other rules that need it, and then use it in the parser like this:

| NUM {$$=mknode($1, NULL, NULL);}

using the usual techniques for declaring the YYUNION and typing the nodes.