[Ktechlab-devel] About unexpected crashes at list iteration and element removing in Qt

Zoltan Padrah zoltan.padrah at gmail.com
Mon Jul 20 07:19:49 UTC 2015


  Hi,

I'm sending this mail to start a discussion as somebody might have an idea  
about why apprently correct code is crashing. I'm sending code examples  
below.

Given the classes and typedefs:

(A)
class Wire : public QObject {
  // no Q_OBJECT here
  ...
};
typedef QList<QPointer<Wire> > WireList;


(B)
class Switch : public QObject {
   Q_OBJECT
  ...
};
typedef QList<Switch*> SwitchList;


and the iteration procedures:

(1)
FooList foo = ...;
for ( FooList::iterator it = foo.begin(); it != foo.end(); )
{
   if ( (*it)->someMethod() )
   {
     it = foo.erase(it);
   } else {
     ++it;
   }
}

(2)
FooList foo = ...;
for ( FooList::iterator it = foo.begin(); it != foo.end(); )
{
   if ( (*it)->someMethod() )
   {
     SwitchList::iterator oldIt = it;
     ++it;
     foo.remove(oldIt);
   } else
     ++it;
}

After some testing, I have found the following results:

For (A) (1): FooList = WireList
Works correctly (address sanitizer doesn't complain)

For (A) (2): FooList = WireList
Crashes at the end of the list because when it is the element before the  
last, then both oldIt it become foo.end(), and then it starts accessing  
freed memory.

For (B) (1): FooList = SwitchList
Crashes at the end of the list; tries to use freed memory, similarly to  
(A)(2)

For (B) (2): FooList = SwitchList
Works correctly (address sanitizer doesn't complain)


I cannot explain why crashes happen/don't happen in each case. In my  
opinion all of the 4 cases are correct and functionally identical; don't  
consider memory leaks here.

Anybody has some idea?

Best regards,

  Zoltan




More information about the Ktechlab-devel mailing list