Hello everyone,
I am trying to write a template class but I get a memory leak. The class is as follows:
Now, when I do something along the lines of
it crashes because it runs out of RAM.
As you can see, what I am trying to do is make something similar to std::vector, but make it so that it accepts arrays of data, as opposed to the simple push_back(). If I try to call Cvector::clear() when I am done adding data, it doesn't free the memory.
How can I fix this memory leak problem?
Thank you.
Regards,
Mr_Cloud
I am trying to write a template class but I get a memory leak. The class is as follows:
template <class T> class Cvector{ public: Cvector(){//pass initial parameters sizeOfStream=0; oldstream=new T; stream=new T; } void addData(T *dataIn, unsigned int size){//main function of class stream=new T[sizeOfStream+size]; for (unsigned int i=0;i<sizeOfStream;i++) stream[i]=oldstream[i]; for (unsigned int i=0;i<size;i++) stream[sizeOfStream+i]=dataIn[i]; sizeOfStream+=size; oldstream=new T[sizeOfStream]; for (unsigned int i=0;i<sizeOfStream;i++) oldstream[i]=stream[i]; } unsigned int size(){//return the size of the array return sizeOfStream; } void clear(){//flush values delete[] stream; delete[] oldstream; sizeOfStream=0; } T *data(){//retrieve the array return stream; } private: T *stream; T *oldstream; unsigned int sizeOfStream; };
Now, when I do something along the lines of
Cvector<double> derp; double *hurr=new double[1024]; for (int i=0;i<1024;i++) hurr[i]=i; for (int i=0;i<1000;i++) derp.addData(hurr,1024);
it crashes because it runs out of RAM.
As you can see, what I am trying to do is make something similar to std::vector, but make it so that it accepts arrays of data, as opposed to the simple push_back(). If I try to call Cvector::clear() when I am done adding data, it doesn't free the memory.
How can I fix this memory leak problem?
Thank you.
Regards,
Mr_Cloud