I am attempting to write my own string class (so I can learn more) and while doing so I noticed I ran into an issue with how the char data is being deleted, when the program closes the destructor of string will be called and there will be a heap error on deleting the data
#include <string.h>
template<typename T>
class String
{
protected:
T* mData;
public:
String(const T* data);
~String();
};
template<typename T>
String<T>::String(const T* data)
{
if(data != NULL)
{
mData = new T[strlen(data)];
strcpy(mData, data);
}
}
template<typename T>
String<T>::~String()
{
if(mData != NULL)
{
delete [] mData;
mData = 0;
}
}
int main(void)
{
String<char> Test("Test");
return(0);
}
You are allocating one item too few, strcpy copies the nul terminating byte as well as the string