Bug Three Answer

The problem is that, in the parameters to f, i might be a reference to the first element of list v. Then when that element is popped out, i is left as a reference to unallocated memory. This bug is particularly hard to detect since, in its current form, that unallocated memory is very likely to both be in a page accessible to the program (hence not causing an illegal page fault) and retain the same data as before, so that object i will still act as if it exists normally.

When I saw this bug in the wild, it was crashing the program in an extremely erratic fashion. Nine times out of ten, everything worked perfectly fine, even when a function similar to this buggy one was being called thousands of times.

The program below reveals the bug clearly by having class A track its own allocation status. Notice that the program never crashes or sets off any alarms, even though it is clearly accessing unallocated memory.

#include <list>
#include <iostream>

using namespace std;

class A {
public:
	A() { id = 0; }
	~A() { id = -1; }

	void g() { cout << "A::g of " << id << endl; }

private:
	int id;
};

void f(list<A> &v, A &i) {
	if (v.size() == 0) return;
	v.pop_front();
	i.g();
}

int main() {
	list<A> v;
	A a;
	v.push_back(a);
	f(v, v.front());

	return 0;
}


Program output:
A::g of -1


Bugs