I have an issue when it comes to preventing memory leaks in my program.
#include <iostream>
using namespace std;
class String
{
public:
String();
String(char str[], int size);
~String();
void clear();
private:
char *data;
int size;
};
String::String()
{
size = 0;
data = NULL;
}
String::String(char str[], int _size)
{
data = new char[_size];
for(int i=0;i<_size;i++)
data[i] = str[i];
size = _size;
}
String::~String()
{
// if(data != NULL)
// delete [] data;
}
void String::clear()
{
if(data != NULL)
delete []data;
size = 0;
}
int main()
{
char temp[] = {'a','b','c','d'};
String str(temp, 4);
str.clear();
}
In this code, I have no memory leaks, but it requires me to manualy deallocate memory by calling the clear method. If I instead uncomment the code within the destructor and delete the str.clear() line, I get an error saying that I am freeing the same memory twice. I am confused because the clear method and destructor contains practially the same code, yet such different results.