Fle*_*515 0 c++ memory-management heap-corruption
我必须为家庭作业创建一个重载的String类.我在测试一些运算符时遇到了问题:
int main() {
MyString i;
cin >> i;
cin.ignore(100, '\n');
MyString temp = i;
while(!(i > temp)) {
temp += i;
cin >> i;
cin.ignore(100, '\n');
}
cout << endl << temp;
return 0;
}
MyString operator+= (const MyString& op1) {
_len += (op1._len);
char* temp = new char[_len+1];
strcpy(temp, _str);
strcat(temp, op1._str);
if(_str) {
delete [] _str;
_str = NULL;
}
_str = new char(_len+1);
strcpy(_str, temp);
return *this;
}
istream& operator>> (istream& inStream, MyString& in) {
char temp[TSIZE];
inStream >> temp;
in._len = strlen(temp);
if(in._str) {
delete [] in._str;
in._str = NULL;
}
in._str = new char[in._len+1];
strcpy(in._str, temp);
return inStream;
}
MyString(const MyString& from) {
_len = from._len;
if(from._str) {
_str = new char[_len+1];
strcpy(_str, from._str);
} else _str = NULL;
}
explicit MyString(const char* from) {
if(from) {
_len = strlen(from);
_str = new char[_len+1];
strcpy(_str, from);
} else {
_len = 0;
_str = NULL;
}
}
Run Code Online (Sandbox Code Playgroud)
我对此仍然很新,但显然问题是第二次调用+ =运算符时出现,而不是第一次.如果我没有提供所需的所有信息,我很抱歉,我不想包含超过需要的内容.感谢您的任何帮助
_str = new char(_len+1);
Run Code Online (Sandbox Code Playgroud)
通过在那里使用括号而不是方括号,您将分配一个char并使用奇怪的值初始化它.我很确定你打算分配一个数组.
_str = new char[_len+1];
Run Code Online (Sandbox Code Playgroud)
但既然你已经分配了temp,为什么不用它呢?
_str = temp;
// strcpy(_str, temp); // delete this line
Run Code Online (Sandbox Code Playgroud)
这也解决了你的内存泄漏问题.您没有释放分配的内存temp,但使用此方法,您不必.