I’ve been writing a basic packet capture utility to implement a couple ideas I’ve had floating around on statistical IDS. Earlier today I had an odd bug. I had a pointer to a vector that after “a while” would randomly be de-referenced. I thought maybe libpcap was causing a concurrency issue and the structure was accidentally de-referenced then. After making some alterations I decided that was unlikely.
Here’s an example piece of what I did:
vector <omg *> * foo()
{
vector <omg *> v;
while(data)
{
//manipulate data
v.push_back(data);
}
return &v;
}
int main()
{
vector * vptr;
while(things_to_do)
{
vptr = foo();
//process vptr
}
}
Don’t nitpick pseudo code for memory management. The problem is actually fairly obvious if you think about it. v formatted in foo() is a stack variable. So it works fine inside the function. It also works fine later, for a while, but then that stack space is re-used and your pointer is dereferenced. As a result you get a bug that will eventually appear no matter how many sanity checks you perform later. The right way to do this is as follows:
vector <omg *> * foo()
{
vector <omg *> * v = new vector <omg *>;
if(!v)
return NULL;
while(data)
{
//manipulate data
v-%gt;push_back(data);
}
return v;
}
This works, because new creates a heap allocation that’s only destroyed with an explicit free/delete. So the repaired code works fine without randomly being de-allocated. The only trick from