Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. QListIterator memory corruption
Qt 6.11 is out! See what's new in the release blog

QListIterator memory corruption

Scheduled Pinned Locked Moved General and Desktop
listiterator
1 Posts 1 Posters 771 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    Simon Parzer
    wrote on last edited by
    #1

    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?

    1 Reply Last reply
    0

    • Login

    • Login or register to search.
    • First post
      Last post
    0
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Search
    • Get Qt Extensions
    • Unsolved