当我尝试在yacc& lex中编译我的代码时,我收到此错误:
yacc代码:
maxAllowedContentLength
和lex 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;
}
当我试图将yytext更改为$ 1时编译但是当我运行代码并输入例如5 + 6时说:(分段错误(核心转储))
使用ubuntu 64:
使用flex版本lex 2.6.0编译lex:
%%
[0-9]+ return NUM;
\+ return PLUS;
\- return MINUS;
%%
和yacc编译与野牛版本野牛(GNU Bison)3.0.4:
lex subProject.lex
和错误提供者:
yacc subProject.yacc
答案 0 :(得分:2)
你根本不应该在语法规则中使用yytext
。它并不总是具有您认为可能具有的价值。您应该将其保存在扫描仪的yyunion
中:
[0-9]+ { yylval.text = strdup(yytext); return NUM; }
并且类似于需要它的其他规则,然后在解析器中使用它:
| NUM {$$=mknode($1, NULL, NULL);}
使用常规技术声明YYUNION
并输入节点。