开发者

Valgrind memory leak reported in QT list append

开发者 https://www.devze.com 2023-04-09 15:19 出处:网络
I am using a serializer in QT C++. It looks ok but valgrind (memcheck tool) is reporting a memory leak on this function.

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?


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.


Valgrind memcheck only tells you that there is a memory leak. If, as in your case, there is one, it reports the function where the memory allocation happened (the new statement).

To get rid of this leak, you have to delete all the elements that have been dynamically allocated. In your case, as Idan K wrote, you can use the generic Qt algorithm qDeleteAll(objAppNodeListRecord)for instance in the destructor of your class or you can use a more explicit version as follow:

foreach (AppNodeRecord *element, objAppNodeListRecord)
{
  delete element;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消