【发布时间】:2018-03-21 19:32:22
【问题描述】:
我有以下一段 C++ 代码,暂时忽略在程序中实际执行此操作的不良做法。
#include<iostream>
//#include <type_traits>
using namespace std;
class P{
public:
void rebase(P* self);
virtual void print();
virtual ~P(){}
};
class C: public P{
virtual void print();
};
void P::rebase(P* self){
//memory leak is detected, but no leak actually happens
delete self;
self=new C();
}
void P::print(){
cout<<"P"<<endl;
}
void C::print(){
cout<<"C"<<endl;
}
int main(){
P *test;
test= new P();
test->print();
for(int i=0;i<10000;i++) test->rebase(test);//run the "leaking" code 10000 times to amplify any leak
test->print();
delete test;
while (true);//blocks program from stoping so we can look at it with pmap
}
我通过 valgrind 发送了这段很糟糕的代码,它在 P::rebase() 中报告了内存泄漏,但是当我查看内存使用情况时没有泄漏,为什么 valgrind 认为有?
==5547== LEAK SUMMARY:
==5547== definitely lost: 80,000 bytes in 10,000 blocks
==5547== indirectly lost: 0 bytes in 0 blocks
==5547== possibly lost: 0 bytes in 0 blocks
==5547== still reachable: 72,704 bytes in 1 blocks
==5547== suppressed: 0 bytes in 0 blocks
==5547== Rerun with --leak-check=full to see details of leaked memory
==5547==
==5547== For counts of detected and suppressed errors, rerun with: -v
==5547== ERROR SUMMARY: 30001 errors from 7 contexts (suppressed: 0 from 0)
我仔细检查了sudo pmap -x,没有泄漏
total kB 13272 2956 180
【问题讨论】:
-
这是一个重要的问题,因为我设计的很多 C 程序都没有在调试器中声明内存问题,但 valgrind 会报告它们。
标签: c++ memory-leaks polymorphism valgrind