I give the code of the overloaded method (some kind of slices) in which a memory leak occurs. Help please find exactly where. Is the local variable temp to be destroyed?
Why does the function not work when assigned temp.size = 0 and works at 11..1? The size class field is used to keep track of the status of a method call. (In case this is the second method call, the size of the string will not match the size field.)
struct String { String(const char *str = "") { this->size=strlen(str); this->str=new char [size+1]; for(int i=0; i < this->size; i++) this->str[i]=str[i]; this->str[size]='\0'; } ~String() { delete [] str; } String(const String &other) { this->size=other.size; this->str=new char [size+1]; for (int i=0; i<=this->size; i++) this->str[i]=other.str[i]; } String& operator=(const String &other) { this->~String(); this->size=other.size; this->str=new char [size]; for (int i=0; i<size; i++) this->str[i]=other.str[i]; return *this; } String operator[](const int ii) const { String temp; if (this->size == strlen(this->str)) { if (ii != 0) temp.size = this->size; else temp.size=111111; temp.str = new char[this->size - ii]; for (int i = ii; i < this->size; i++) temp.str[i - ii] = this->str[i]; } else { if (this->size==111111) temp.size=ii; else temp.size=strlen(this->str)+ii-this->size; temp.str=new char [temp.size]; for (int i=0; i<temp.size; i++) temp.str[i]=this->str[i]; } return temp; } public: size_t size; char *str; }; ostream& operator<<(ostream & os, const String &a) { os << a.str; return os; } int main() { String a; a=String("asdasd"); String b=a[2][3]; b=a[0][2]; cout << b << endl; String const hello("hello"); String const hell = hello[0][4]; // теперь в hell хранится подстрока "hell" String const ell = hello[1][4]; // теперь в ell хранится подстрока "ell" cout << hello << " " << hello.size << endl; cout << hell << " " << hell.size << endl; cout << ell << " " << ell.size << endl; return 0; }
String
. - VladD