问题
I am new to lex and yacc programs.I have been trying to write a yacc program which takes as input an arithmetic expression and gives prefix notation as output. here is my lex code.
%{
#include<string.h>
#include"pre.tab.h"
%}
%%
"*"|"/"|"+"|"-"|"("|")" {return yytext[0];}
[0-9]+ {yylval.name=(char*)malloc(yyleng+1);
strcpy(yylval.name,yytext);
return NUM;}
\n {return(0);}
[a-zA-Z][a-zA-Z]* {yylval.name=(char*)malloc(yyleng+1);
strcpy(yylval.name,yytext);
return ID;}
. {}
%%
int yywrap()
{
return 1;
}
Here is my YACC code
%{
#include<stdio.h>
#include<string.h>
char buf[10];
%}
%union
{
char *name;
}
%token<name>NUM ID
%type<name>E
%left'+''-'
%left'*''/'
%nonassoc UMINUS
%%
S:E {printf("\n%s",$1);}
;
E:E'*'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"*"),strcat($1,$3)));}
|E'/'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"/"),strcat($1,$3)));}
|E'+'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"+"),strcat($1,$3)));}
|E'-'E {buf[0]='\0';strcpy($$,strcat(strcpy(buf,"-"),strcat($1,$3)));}
|ID
|NUM
|'('E')'{strcpy($$,$2);}
;
%%
main()
{
yyparse();
}
int yyerror(char *s) {fprintf(stderr,"%s\n",s);}
I am not getting any output when I input an arithmetic expression in parantheses. Eg : Input : 1+(2*3) output : +*23*23. I have tried to rectify the code many times but in vain.
回答1:
In C, strings do not magically expand like they do in other languages. (Or, better said, there really is no string object.) You cannot call strcat(a, b)
unless you have already ensured that the char array a
has enough space following the NUL terminator to append b
.
You can't strcat
to a string literal, because not only is there not enough space, but also the string literal may be in read-only memory.
And you can't strcpy to an unassigned variable and expect sufficient memory to be allocated automatically. (Although $$
is not actually an uninitialised variable, since it is initialised to the value of $1
.)
So your code is full of buffer overruns, which is undefined behaviour.
来源:https://stackoverflow.com/questions/36383448/lex-and-yacc-program-to-convert-infix-to-prefix