分割故障c++
segmentation fault c++
我得到一个分割错误,我不知道如何调试它!它发生在创建了MyString
数组之后,即创建了没有任何问题的数组。
void ConcatTest()
{
cout << "n----- Testing concatentation on MyStringsn";
const MyString s[] =
{MyString("outrageous"), MyString("milk"), MyString(""),
MyString("cow"), MyString("bell")};
for (int i = 0; i < 4; i++) {
cout << s[i] << " + " << s[i+1] << " = " << s[i] + s[i+1] << endl;
}
}
我想可能是我重载+操作符的方式有问题:
MyString operator+(MyString str1, MyString str2)
{
MyString resultStr = MyString();
delete [] resultStr.pString;
resultStr.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1];
MyString temp = MyString();
delete [] temp.pString;
temp.pString = new char[strlen(str1.pString) + 1];
strcpy(temp.pString, str1.pString);
delete [] str1.pString;
str1.pString = new char[strlen(str1.pString) + strlen(str2.pString) + 1];
strcpy(str1.pString, temp.pString);
strcat(str1.pString, str2.pString);
strcpy(resultStr.pString, str1.pString);
return resultStr;
}
任何形式的帮助或建议将不胜感激!
您在+
方法进行到一半的时候尝试delete str1.pString
,但str1
作为const MyString
传递,它指向程序中的静态字符串。你不能释放它!
很可能是这个原因。您不应该修改操作符中的str1
或str2
。
如果我正确理解了你的程序,你想修改输入字符串。要做到这一点,必须使用真实的 char[]
字符数组来构造初始MyString
,而不是像"无耻"这样的静态引号字符串。
char* ch1="outrageous"; // ch1 points to a nonmutable memory area
char* str1 = new char[strlen(ch1)]; // str1 now points to a mutable region of memory
strcpy(str1,ch1); // that mutable region now contains the static string
MyString string1 = new MyString(str1); // this string is now writable/changeable
this string1
现在是可变的;
相关文章:
- 分段故障(堆芯转储)矢量
- C++中的动态铸造故障
- 数组的指针从不分段故障
- vscode g++链路故障:体系结构x86_64的未定义符号
- 访问被拒绝后,c++中的故障保护代码
- Windows 10-使用gtkmm-3.0库和g++[包括再现]的分段故障
- 调试 CUDA MMU 故障
- Geeksforgeeks C 程序故障排除:IEE 754 表示法为十进制
- Arch Linux.AUR 包 mysql 不能用 makepkg 构建.错误:构建 () 中出现故障
- 正在处理故障(堆芯转储)
- 在 Boost::fiber 中引发的BOOST_ASSERT故障 Visual Studio "Debug" 构建
- 如何进行故障排除:未定义对"非虚拟 thunk to ..."的引用
- C++函数过载会导致 SEG 故障
- 分段故障 运行C++代码时出现 SIGSEGV
- 当新的故障时,是否有必要留出一些紧急内存?
- Python & C-C++ 扩展模块案例段故障
- 带升压的 SEG 故障::make_shared / 特征3 内存.h.
- 在 c++ 中,发生故障后是否需要 stream.clear()?
- 分段故障背包问题
- 分段故障 11,从类函数显示动态 C 字符串