[英]Valgrind memory leak reported in QT list append
I am using a serializer in QT C++. 我在QT C ++中使用序列化器。 It looks ok but valgrind (memcheck tool) is reporting a memory leak on this function.
看起来还可以,但是valgrind(内存检查工具)正在报告此函数的内存泄漏。
Valgrind cmd: valgrind --tool=memcheck --leak-check=full
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. Valgrind报告此实例未释放,但已在QList中使用。
AppNodeRecord *tmp=new AppNodeRecord;
Valgrind output: Valgrind输出:
==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? 可能是一个valgrind问题吗?
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). QList
不负责释放附加到其上的AppNodeRecord
指针,您必须手动执行(在这种情况下, qDeleteAll
可能会有所帮助)。
But as usual, for lack of a good reason, use QList<AppNodeRecord>
to avoid this hassle in the first place. 但是像往常一样,由于缺乏充分的理由,请使用
QList<AppNodeRecord>
首先避免这种麻烦。
Valgrind memcheck only tells you that there is a memory leak. Valgrind memcheck仅告诉您内存泄漏。 If, as in your case, there is one, it reports the function where the memory allocation happened (the
new
statement). 如果像您的情况那样有一个,它将报告发生内存分配的函数(
new
语句)。
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: 对于您的情况,如Idan K所写,您可以在类的析构函数中使用通用Qt算法
qDeleteAll(objAppNodeListRecord)
,也可以使用以下更明确的版本:
foreach (AppNodeRecord *element, objAppNodeListRecord)
{
delete element;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.