UPDATE:为str1的新数据分配内存。仍有内存错误。
我正在尝试为我创建的字符串类重写+ =方法。
Class mystring{
public:
friend void operator+=(mystring& str1, const mystring& str2){
mystring temp;
delete[] temp.data;
temp.length = str1.length + str2.length;
temp.data = new char[temp.length + 1];
strcpy(temp.data, str1.data);
strcat(temp.data, str2.data);
delete[] str1.data;
str1.length = temp.length;
strcpy(str1.data, temp.data);
}
private:
char *data;
int length;
}
然后在主要课程中:
mystring str1("hi");
mystring str2("matt");
str1 += str2;
cout << str1 << endl;
这个函数应该正常工作,但是当我运行valgrind时,我得到了内存错误。我无法弄清楚为什么会这样。如果有人能给我任何令人敬畏的提示。
由于
答案 0 :(得分:2)
您需要在str1
中分配额外的内存。
你不能盲目地复制到数组末尾。
答案 1 :(得分:2)
首先,你的意思不是:
strcat(str1.data, str1.data);
但:
strcat(str1.data, str2.data);
其次,您希望str2.data
去哪儿?这是一个记忆涂鸦,因此是valgrind错误。惊讶它不只是崩溃。
您需要为组合长度重新分配足够的存储空间,复制原始字符串并释放str1.data
,然后再将其重新分配给新存储空间。
根据更新的帖子:
friend void operator+=(mystring& str1, const mystring& str2)
{
// Not using a temp mystring here, as the temp never really maintains its state as a mystring
// I am assuming length is the length of the string, not the storage. Not the best design if you consider resizing the the string to less than the storage
int newStringLength = str1.length + str2.length;
char* newStorage = new char[newStringLength + 1];
strcpy(newStorage, str1.data);
// strcat has to scan from the start of the string; we do not need to.
strcpy(newStorage + str1.length, str2.data);
delete[] str1.data;
str1.length = newStringLength ;
str1.data = newStorage;
// Haven't though about the case where str2 is an alias for str1.
}
答案 2 :(得分:1)
您必须分配堆来保存字符并在不再需要时释放堆。
这样的事情:
data=new char[length+1];
答案 3 :(得分:1)
//it is strange that operator += return void
// usually we have T& operator += (T const&, T const&)
//or T& T::operator +=(T const&)
friend void operator+=(mystring& str1, const mystring& str2){
//make sure str1 and str2 are correclty initialzed
str1.length = str1.length + str2.length;
//make sure str1.data has enough memory to hold all the data
//make sure str1.data and str2.data are null terminated strings, not binary data
strcat(str1.data, str2.data);
}