Reputation: 315
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. 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. If it is indeed the problem with new and delete, how can I correct this? Thanks.
Upvotes: 0
Views: 114
Reputation: 206526
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. 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.
Upvotes: 1