I'm writing a re-sizable array class (std::vector), as an exercise, using manual pointers (because I want to know how they work before I start using smart pointers). However, Valgrind reports a memory leak at the checkMax() function.
template <typename T>
class Array{
public:
Array() : len(0),maxLen(1){
array=new T[maxLen];
// ........
}
Array(unsigned length, T&content=0) : len(length),maxLen(length*2){
array=new T[maxLen];
//..............
}
~Array(){
//delete[] array;
}
//..............
void push_back(const T& content){
checkMax();
// do stuff...
}
private:
T* array;
unsigned int len;
unsigned int maxLen;
..
void checkMax(){
if(len==maxLen){
//allocate more memory for the array
maxLen*=2;
T*temp=new T[maxLen]; // ------------- MEMORY LEAK HERE -------------
for(unsigned int i=0; i<len; i++){
temp[i]=array[i];
}
delete [] array;
array=temp;
}
}
};
I have posted only the memory-relevant code here.
I do not understand why Valgrind is reporting a memory leak at the specified line. I do delete the old array after copying the old array contents to the enlarged array, two lines later.
Also, if I un-comment the delete[] function at the destructor, I get an exception double free or corruption
and Valgrind reports an Invalid Delete(implying re-deletion), so I am totally flummoxed.
Any ideas?
EDIT: Thanks for the early replies! After reading the comments, I found that the problem lies not with my class, but with another function I was calling with the Array class as an argument . If I remove the call to this function, and added the delete call in the class, no memory leaks occur. Here is my function:
template <typename T>
void printContents(Array<T> ar){
for(unsigned int i=0; i<ar.size(); i++){
cout<<"Content at i in array = " << ar.at(i) << endl;
}
}
After reading the Rule of Three(thanks to chris) and the answer posted by Grizzly, I have now understood why the delete[] was invalid. Because I had not overloaded the copy constructor, shallow copying occured, due to which, my array pointer got assigned to the pointer in ar, and when ar when out of scope, the delete[] was called, thereby making my delete in the main function invalid . Hence, I was getting the exception. If I removed the delete, then the array would obviously remain allocated and result in a memory leak.
Thanks for the help, I have voted Grizzly's answer as correct.