Zain Syed
Zain Syed

Reputation: 463

Dereferenced list iterator segfault

I'm putting together a parser for a language in bison/flex and have been implementing the abstract syntax tree. As soon as I implemented some very primitive static type checking though, I've started to get segmentation faults on my list iterator, that is iterating through my statements list.

The root program node that holds the list iterator:

program::program(list<statement *> *stmtList) : stmts(stmtList) {}

void program::evaluate() {
   list<statement *>::iterator stmtIter;
   for (stmtIter = stmts->begin(); stmtIter != stmts->end();
      stmtIter++) {
     (*stmtIter)->evaluate();
  }
}

stmtList is a pointer to a list of pointers to statements. it has to be a pointer to a list because bison to accomodate bison not accepting types requiring constructors in %union

an example of a statement node that it is failing upon is

void declare_assign_stmt::evaluate() 
{
    reference * ref;
    ref->type = type;

    if(ref->type != exp->type)
    {
        cerr << "Incompatible types!" << endl;
    }
    else {
        ref->location = exp->evaluate();;
        idTable[id] = ref;
    };

}

reference is a struct with two fields, type and location, a string and int respectively. idTable is a map of id's to reference pointers. exp is a pointer to my expression node, and it evaluates correctly and returns an int. i've stepped through this function and everything behaves as expected, but upon completing evaluate(), it will return to the iteration loop, and even if the list contained no more elements, the loop will continue and (*stmtIter) will next point to a location where no statement exists, thus giving the segmentation fault. nothing within a statements evaluation manipulates the list.

some insight would be great. thanks!

Upvotes: 0

Views: 588

Answers (1)

Roland Illig
Roland Illig

Reputation: 41676

reference * ref;
ref->type = type;

You did not initialize that pointer. The compiler should really warn you about that. Did you enable all available compiler warnings?

Upvotes: 2

Related Questions