This is the C++ program I have written, this program creates a class String containing two attributes str (used for storing character string) and len (used for storing length of the string):
#include<iostream>
#include<string.h>
using namespace std;
class String {
char *str;
int len;
public:
String();
String(const char*);
String(const String&);
~String();
friend String operator + (const String&, const String&);
friend bool operator <= (const String&, const String&);
friend ostream& operator << (ostream&, const String&);
};
String::String(void)
{
// Default constructor of the class String
str=NULL;
len=0;
}
String::String(const char* cp)
{
// Parametrized constructor of the class String
len=strlen(cp);
str=new char[len+1];
strcpy(str, cp);
}
String::String(const String& str1)
{
// Copy constructor of the class String
len=str1.len;
str=new char[len+1];
strcpy(str, str1.str);
}
String::~String(void)
{
// Destructor of the class String to
// free the heap memory allocated using new operator
delete[] str;
}
String operator + (const String& str1, const String& str2)
{
// Overload + operator to concatenate two strings and
// return the object of class String containing the cocatanated string
String str3;
str3.len=str1.len+str2.len;
str3.str=new char[str3.len+1];
strcpy(str3.str, str1.str);
strcat(str3.str, str2.str);
return str3;
}
bool operator <= (const String& str1, const String& str2)
{
// Overload <= operator to compare two objects of class String
if(str1.len<=str2.len)
return true;
else
return false;
}
ostream& operator << (ostream& dout, const String& str1)
{
// Overload << operator to print the string using object name of class String
dout<<str1.str;
return dout;
}
int main()
{
String s1="New";
String s2="York";
char capital[]="Delhi";
String s3=capital;
String string1, string2, string3;
string1=s1;
string2=s2;
string3=s1+s3;
cout<<string1<<endl;
cout<<string2<<endl;
cout<<string3<<endl;
return 0;
}
after running this program with g++, I got this error message:
New
York
NewDelhi
test(2922,0x10f07ce00) malloc: *** error for object 0x7fb438c05a70: pointer being freed was not allocated
test(2922,0x10f07ce00) malloc: *** set a breakpoint in malloc_error_break to debug
fish: Job 1, './test' terminated by signal SIGABRT (Abort)
Looks like some heap memory is getting freed twice or an unallocated memory is getting freed. I am unable to figure out where the program went wrong.