I am writing my own String class and have overloaded some of the operators for convenience. But I ran into a problem while using one of these overloaded operators.
Following is the driver code:
String str1 {"Hello"};
String str2 {"World"};
String str3 = str1 + str2;
The above driver code compiled fine but generated the following error when I executed the binary:
free(): double free detected in tcache 2
Aborted (core dumped)
When I commented the last line of the driver code, the file compiled and executed fine. So apparently the problem lies in the third line where I tried using the overloaded + operator which is meant to facilitate concatenation. But still I am not able to spot exactly where the problem is.
Following is the code for destructor:
String::~String() {
if(this->str != nullptr)
delete [] this->str;
}
And following is the code for overloaded + operator:
// + overloaded for concatenation of strings
String String::operator+(String &rhs) {
char *temp_str;
temp_str = new char[std::strlen(this->str) + std::strlen(rhs.str) + 1];
temp_str = std::strcat(str, rhs.str);
String temp_obj {temp_str};
delete [] temp_str;
return temp_obj;
}
Following are the constructors:
// Default constructor
String::String(): String(nullptr) {}
// Parameterised constructor
String::String(const char *s): str {nullptr} {
if(s == nullptr) {
str = new char;
*str = '\0';
}
else {
str = new char[std::strlen(s) + 1];
std::strcpy(str, s);
}
}
I have also overloaded the = operator for copying and moving objects. Below is the implementation:
// = overloaded to copy a String object
String& String::operator=(const String &rhs) {
if(this == &rhs)
return *this;
delete [] str;
str = new char[std::strlen(rhs.str) + 1];
std::strcpy(str, rhs.str);
return *this;
}
// = overloaded to move a String object
String& String::operator=(String &&rhs) {
if(this == &rhs)
return *this;
str = rhs.str;
rhs.str = nullptr;
return *this;
}