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.