I am using C++ 98. When I try to run the below code and note the task manager - the memory consumption goes very high. Can someone explain if there is a leak in the commented part in main
, if so how could this be fixed?
#include <iostream>
#include<vector>
using namespace std;
template<typename T> class ArrayHandler
{
public:
ArrayHandler()
{
val=NULL;
count=0;
}
~ArrayHandler()
{
freecontent();
}
void assign(T* p, int32_t icount)
{
freecontent();
count=icount;
val= new T[count];
for(int32_t i=0;i<icount;i++)
{
val[i]=p[i];
}
}
void resize(int32_t newsize)
{
if(newsize==count)
return ;
else
{
T* p= new T[newsize];
int32_t maxcount= count-1;
for(int32_t i=0; i< maxcount;i++)
{
if(maxcount>i)
p[i]= val[i];
else
p[i]= val[maxcount];
}
assign(p, newsize);
}
}
private:
T* val;
int32_t count;
void freecontent()
{
delete[] val;
val=NULL;
}
};
template<typename T> void handlesettingsize(T* p, ArrayHandler<T>& val, int32_t icount)
{
val.assign(p,icount);
if(icount==4)
{
//do nothing
}
else
{
val.resize(100);
}
}
int main()
{
ArrayHandler<double> val;
for(int32_t i=0;i<15000;i++)
{
double *p =new double[6];
for(int32_t i=0;i<6;i++)
p[i]=0.0+i;
handlesettingsize(p, val, 5); // Task manager shows increased memory consumption if not commented
delete[] p;
p=NULL;
}
return 0;
}