Tuesday, September 26, 2006

Long day

Worked from 9am to 9:30pm. Turns up I introduced a bug last Thursday and it was subtle enough that it took all evening to track it down.

Programmers, start your engines!

Here is the function I wrote, with the intention of removing all unused entries from the end of the STL vector called _db (dead entries have their value set to NULL). See if you can spot the problem:

void DagentStateImpl::compact_dblist()
{
if (_db.size() > 0) {
unsigned int i;
for(i = (_db.size() - 1); i > 0; i--) {
if (_db[i] != NULL)
// We've hit a real entry so don't go any further
break;
}
if (i < _db.size())
_db.resize(i);
}
}


If you can spot the bug and want to work in a penthouse overlooking the Flatiron, then you should send me your resume.

I'm also looking for a cleaner solution. I know I could put the resize() inside the loop, which would be much easier to follow, but I didn't want to incur the cost of doing resize multiple times if there were lots of entries to remove when I could just do it once at the end once I knew what the new size should be. A reverse iterator would make the for loop cleaner but I would still need to keep track of the index so I would know what to resize to (which kind of defeats the purpose of using a reverse iterator in the first place).