views:

169

answers:

1

I'm writing a simplified Pascal parser/interpreter and now I'm thinking about segmentation faults. I'm not getting them yet, everything is running fine, but since I'm developing under Cygwin, I can't test the program through valgrind.

Basically what I'm doing is described below:

typedef struct{
    char idType; //Integer (i), Real (r), Char (c), String (s) or Function (f)
    union{
         int intValue;
     double fltValue;
     char chrValue;
     char *strValue;
    }idValue;
}symrec;
.
.
.
%union{
    symrec *symbol;
}
.
.
.
%destructor {
    if($$->idType == 's'){
     free($$->idValue.strValue);
    }
    free($$);
} tIdentifier tLiteralString tLiteralChar tLiteralInteger tLiteralReal

Of course, tokens are typed correctly and everything. The problem is when negating some expressions, for example. I usually reuse some symrec * instead of malloc a new one.

Example:

pArithmetic: tMinus pExpression { $$ = -$2; }

Of course, this is not valid in my context (in the example I just considered int or double as the datatype), I'm parsing the symrec * properly, but in this scenario, won't the destructor dealloc $2 leaving $$ as some kind of dangling pointer?

As of writing this I'm thinking, if this really happens and gets me some segfaults, may I just make $2 = NULL; and check that in the %destructor{} clause?

PS: I'm not an English native speaker and I've made this quite long, so I beg your pardon for any confused ideas, which I'll promptly re-explain.

+1  A: 

No, %destructors are only called when the parser is throwing away symbols as part of error recovery.

When a rule matches, the ownership of symbols should either be transferred, usually to $$, or destroyed in the rule. So your unary minus example does not have dangling pointers.

To find your segfaults, I suggest you run your code under gdb.

laalto
I don't know exactly at what point, but segfaults are gone!So, I can use the same general rule for %destructors as the normal destruction, then, except that they'll be called by the error recovery system. Thank you for the clarification.
Spidey