QListIterator memory corruption
-
Hello! I have a little trouble understanding how QListIterator/QMutableListIterator work.
The following example is based on a real world application, I just isolated the problematic code so it's easier to understand.
If you want to try it, just create a new console application in Qt Creator and replace main.cpp with this code. I used the precompiled Qt 5.4.2 SDK with the MinGW compiler.#include <QCoreApplication> #include <QDebug> struct A { A(): a(1), b(1), c(3) {} int a, b, c; }; struct B { QList<A> list; void inner() { QMutableListIterator<A> it(list); while (it.hasNext()) { it.next().b++; } } }; static B b; int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); for (int i = 0; i < 10; i++) { A a; b.list.append(a); } A* first = &b.list[0]; { QListIterator<A> it(b.list); while (it.hasNext()) { const A& elem = it.next(); qDebug() << elem.a << elem.b << elem.c; } b.inner(); qDebug() << first->a << first->b << first->c; } qDebug() << first->a << first->b << first->c; return a.exec(); }
Here is the output:
1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 1 1 3 -17891602 -17891602 -17891602
The last two lines puzzle me. I was expecting them both to say "1 2 3", but instead ~QListIterator destructed the list, and I'm reading deallocated memory.
Is this how it is supposed to work, and if yes, why?