【发布时间】:2017-03-30 18:20:56
【问题描述】:
我是 Flex/Bison 的新手。我只想对值使用字符串(是语言翻译器)。我有这个供测试:
example.l:
%option noyywrap nodefault
%{
#include <string.h>
#include "example.tab.h"
%}
%%
[ \t\n] {;}
"<=" {return LEFT;}
"=>" {return RIGHT;}
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
. { return yytext[0]; }
%%
example.y:
%{
#include <stdio.h>
#define YYSTYPE char const *
%}
%token NUMBER
%token LEFT "<=" RIGHT "=>"
%%
start: %empty | start tokens
tokens:
NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); }
| NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); }
| NUMBER '>' NUMBER { printf("%s > %s\n",$1,$3); }
| NUMBER '<' NUMBER { printf("%s < %s\n",$1,$3); }
%%
main(int argc, char **argv) { yyparse(); }
yyerror(char *s) { fprintf(stderr, "error: %s\n", s); }
当我编译时:
bison -d example.y
flex example.l
cc -o example example.tab.c lex.yy.c -lfl
example.l: In function ‘yylex’:
example.l:13:9: warning: assignment makes integer from pointer without a cast
[0-9]+ { yylval=strdup(yytext); return NUMBER; }
^
但按预期工作。
如果我不使用 #define YYSTYPE char const * 而使用 %union:
%union {
char * txt;
}
%token <txt> NUMBER
并将分配更改为[0-9]+ { yylval.txt=strdup(yytext); return NUMBER; },它没有警告并且可以工作。
我尝试过在 flex 文件中定义相同的 YYSTYPE 并进行分配但没有成功。怎么了?如何在不使用 %union 的情况下修复?
谢谢。
【问题讨论】:
-
为避免内存泄漏,您需要将 YYSTYPE 用作
char *并执行 free():NUMBER "<=" NUMBER { printf("%s <= %s\n",$1,$3); free($1); free($3);} | | NUMBER "=>" NUMBER { printf("%s => %s\n",$1,$3); free($1); free($3);}等等。您可以使用 valgrind valgrind.org 检查您的程序是否有免费的内存泄漏 -
太棒了!最后一个示例包括您的建议。
标签: bison flex-lexer