Hi,

I'm resending mail previous message, because it has not been
successfully sent. Sourceforge had a storage fault and most of the
sf.net has been taken offline. Now the mailing lists should work.


---------- Forwarded message ----------
From: Zoltan Padrah <zoltan.pad...@gmail.com>
Date: 2015-07-20 10:19 GMT+03:00
Subject: About unexpected crashes at list iteration and element removing in Qt
To: "ktechlab-devel@lists.sourceforge.net"
<ktechlab-devel@lists.sourceforge.net>



 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

------------------------------------------------------------------------------
_______________________________________________
Ktechlab-devel mailing list
Ktechlab-devel@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/ktechlab-devel

Reply via email to