lex and yacc program to convert infix to prefix

回眸只為那壹抹淺笑 提交于 2019-12-11 23:15:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!