Pergunta

This code works perfectly fine. After compiling lex and yacc, the code is able to do basic arithmetic operations, and even echoes the value of a variable when asked to do so. The only problem is with assignment statements.

If I want to, say, do A = 12, and later type A to see its value, the program crashes and I get a segmentation fault. How do I ensure that my assignment statements work, and how can I avoid this segmentation fault?

Here is my code:

//lex file

/*Lex input specification*/
%{
#include <stdlib.h>
#include <stdio.h>
#include "y.tab.h"
void yyerror(char*);
%}

%%
" "             ;

[A-Z]               { yylval = *yytext-'a'; return VARIABLE;}

[0-9]+([0-9])*          { yylval=atoi(yytext); return INTEGER;}

[-/+()=*\n]         { return *yytext;}


[\t]                ;

.               { yyerror("invalid character");}
%%

int yywrap(void) { return 1;}

And the yacc file:

/*yacc*/

%token INTEGER VARIABLE
%left '|'
%left '&'
%left '+' '-'
%left '*' '/'
%left UMINUS



%{
    void yyerror(char*);
    int yylex(void);
    int sym[26];

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>

%}

%%

program:
        program statement '\n'
        |
        ;
statement:
        expr            {printf("%d\n",$1);}
        | VARIABLE '=' expr     {sym[$1] = $3;}
        ;

expr:

        INTEGER         {$$ = $1;}
        | VARIABLE      {$$ = sym[$1];}
        | expr '*' expr     {$$ = $1 * $3;}
        | expr '/' expr     {$$ = $1 / $3;}
        | expr '+' expr     {$$ = $1 + $3;}
        | expr '-' expr     {$$ = $1 - $3;}
        | '(' expr ')'      {$$ = $2;}
        ;
%%

void yyerror(char*s) {
    fprintf(stderr, "%s\n", s);
}

int main(void) {
    yyparse();
    return 0;

}

Nenhuma solução correta

Outras dicas

(I flagged this as "not reproducible" because the fix was so trivial; however the flag has now timed-out/aged away. I'll answer instead so it is not shown as an open unanswered question).

As @BLUEPIXY noted:

maybe *yytext-'A'

Which, to clarify, is the lex rule:

[A-Z]               { yylval = *yytext-'A'; return VARIABLE;}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top