Wednesday, April 24, 2013

Race Conditions Resulting in Double Free

In working with Qt and its slot and signals, I've encountered quite a few double free errors despite my use of QSharedPointer. One particularly puzzling situation, I have stumbled upon involves the following model:

  1. An object, say controller, owns another object, say agent
  2. Controller subscribes to a event (signal) from agent called closing
  3. If the agent issues a closing signal, the controller removes it from a list of known agents (effectively freeing it as a result of the QSharedPointer).
  4. If the controller is closing, it calls close on the agents and then removes them from its list.
The double free occurs when the controller closes before the agents, effectively causing the agent to notify the controller it is being closed while both are being destructed. This probably occurs because the Qt signal disconnect code would happen in the base destructor (QObject), which would be called after the Session destructor. The easy resolution was to disconnect all signals except destroyed.