Search code examples
c++qtmemory-leaksvalgrindqlist

Valgrind memory leak reported in QT list append


I am using a serializer in QT C++. It looks ok but valgrind (memcheck tool) is reporting a memory leak on this function.

Valgrind cmd: valgrind --tool=memcheck --leak-check=full

QDataStream &operator>>( QDataStream &in, QList<AppNodeRecord *> *objAppNodeListRecord)
{
    quint32 len;
    in >> len;

    objAppNodeListRecord->clear();
    for(quint32 i = 0; i < len; ++i)
    {
        AppNodeRecord *tmp=new AppNodeRecord;
        in >> tmp;
        objAppNodeListRecord->append(tmp);

        if (in.atEnd())
            break;
    }
    return in;
}

Valgrind reports that this instance is not freed but it is been used in the QList.

AppNodeRecord *tmp=new AppNodeRecord;

Valgrind output:

==19503== 1,445 (68 direct, 1,377 indirect) bytes in 1 blocks are definitely lost in loss record 1,540 of 1,568
==19503==    at 0x4026351: operator new(unsigned int) (vg_replace_malloc.c:255)
==19503==    by 0x8058562: operator>>(QDataStream&, QList<AppNodeRecord*>*) (zbDbs_NodeMgmt.cpp:206)
==19503==    by 0x804D53C: main (main.cpp:53)

Could it be a valgrind issue?


Solution

  • The QList isn't responsible for deallocating the AppNodeRecord pointers you append to it, you have to do it manually (qDeleteAll might help in that case).

    But as usual, for lack of a good reason, use QList<AppNodeRecord> to avoid this hassle in the first place.