简体   繁体   English

新的和删除的内存泄漏

[英]Memory leak with new and delete

I tried to modify some previous code but find that the memory the program used keep increasing as it runs. 我尝试修改一些先前的代码,但是发现程序运行时使用的内存一直在增加。 So there might be a memory leak. 因此可能存在内存泄漏。 The major part of my code contains the following loop 我的代码的主要部分包含以下循环

CEnergymulti* ener;
double potential;
double pottemp;

potential=0.0;
pottemp=0.0;

for(int i=0;i<nbin;i++)
{
 ener = new CEnergymulti(np1,molfnames1,idiel);
  pottemp=ener->calculatePot(ener->m_mols);
  potential+=pottemp;
 delete ener;
}

where 'CEnergymulti' is a class. 其中“ CEnergymulti”是一类。 I suspect the repeated use of new and delete may cause the memory leak problem, since if I just perform a single run for the code within the loop, I didn't see increase in memory during running. 我怀疑重复使用new和delete可能会导致内存泄漏问题,因为如果我只对循环中的代码执行一次运行,则在运行期间不会看到内存增加。 If it is indeed the problem with new and delete, how can I correct this? 如果确实是new和delete的问题,我该如何解决? Thanks. 谢谢。

There is no memory leak in the code you show( Unless there is a badly implemented destructor for CEnergymulti )But there is no compelling reason to use dynamically allocated object to begin with. 您显示的代码中没有内存泄漏( 除非CEnergymulti析构函数实现CEnergymulti ),但没有令人信服的理由开始使用动态分配的对象。 Why not simply use: 为什么不简单使用:

CEnergymulti obj;
pottemp=obj.calculatePot(obj.m_mols);
potential+=pottemp;

Drop the uneeded new and delete and you don't have to bother about manual memory mangement anymore. 删除不需要的newdelete ,您不必再为手动内存管理而烦恼了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM