Reputation: 5745
I have this simple code (for making things shorted, the important bits are probably only the constructor and the add method.) (Code updated).
#include "general.h"
template <class T>
class Template
{
private:
T* oldArr;
T* newArr;
int oldArrTop;
int oldArrLen;
public:
Template();
~Template();
void add(const T& val);
void print();
};
template <class T>
Template<T>::Template()
{
oldArr=new T[2];
oldArrTop=0;
oldArrLen=2;
newArr=new T[4];
//newArr's length is always 2.
}
template <class T>
Template<T>::~Template()
{
delete[] oldArr;
delete[] newArr;
}
template <class T>
void Template<T>::add(const T& val)
{
//add normally
oldArr[oldArrTop]=val;
//need to copy 2 elements
if( oldArrTop%2==1 )
{
newArr[oldArrTop]=oldArr[oldArrTop];
newArr[oldArrTop-1]=oldArr[oldArrTop-1];
}
oldArrTop++;
//need to double array's size
if( oldArrTop==oldArrLen )
{
delete[] oldArr;
oldArr=newArr;
oldArrLen*=2;
newArr=new T[oldArrLen*2];
}
}
template <class T>
void Template<T>::print()
{
for (int i=0; i<oldArrTop; i++)
cout<<oldArr[i]<<endl;
}
Here's the code that uses the template:
Template<int> a=Template<int>();
for(int i=0;i<10;i++)
a.add(i);
a.print();
However, when I used the template with integers (for example), the first time I delete an array (the first time I get into the "need to doube array's size" part in add, I get a heap corruption error. Anyone knows what the problem is? Thank you very much!
I'm not sure what fixed it, but the heap corruption error is gone. But, instead of printing the numbers from 0 to 9, it just prints a weird number (-842105421). Any ideas why?
Upvotes: 0
Views: 1086
Reputation:
I think you can here access memory behind your allocated area:
oldArr[oldArrTop]=newArr[oldArrTop];
When you are adding the second value oldArrTop will become 2 and you will enter if( oldArrTop%2==0 )
. And in this if your oldArr
has only two allocated elements but you try to access the third one (since oldArrTop==2 and it means the third element):
oldArr[2]=newArr[2];
Upvotes: 3
Reputation: 27581
Just use std::vector<T>
. It will manage memory for you (and will double array size if needed :) )
Upvotes: 1