I am implementing a string class in C++, and I have come across an issue when trying to delete the char[] that contains the data of the string:
class String
{
public:
String();
String(char str[], int size);
~String();
void clear();
private:
char *data;
int size;
};
String::String()
{
size = 0;
}
String::String(char str[], int _size)
{
data = str;
size = _size;
}
String::~String() {}
void String::clear()
{
if(size > 0)
delete []data;
size = 0;
}
int main()
{
char temp[] = {'a','b','c','d'};
String str(temp, 4);
str.clear();
}
This code results in an error, VSCode simply says "Exception has occurred. Unknown signal" and the program crashes once the delete []data line is reached. The program works without this line, but I want to prevent memory leaks.
I've tried to declare a char* and assing that to new char[4], and from there populate each value one by one. This did nothing. Looking in the debugger, the correct array is assigned to data in str, so I memory does indeed seem to be allocated to the program, yet I just do not understand why I cannot delete the array. Is it const for some reason? Any thoughs?