c++ - C++ 错误:在抛出 'std::bad_alloc' 的实例后终止调用
问题描述
我创建了一个用户定义的 String 类和一些文件处理函数。我之前尝试在 ubuntu 上使用 g++ 编译这段代码和 gdb 调试几次。错误被抛出
s2.diskIn(iflile);
界面:
class String {
long unsigned int len;
char *cStr;
public:
String(const String &);
explicit String(const char * const = NULL);
void diskIn(std::ifstream &);
void diskOut(std::ofstream &);
const char *getString();
String operator = (const String);
~String();
};
复制构造函数
String::String(const String &ss) {
if (ss.cStr == NULL) {
cStr = NULL; len = 0;
} else {
len = ss.len;
cStr = new char[len + 1];
strcpy(cStr, ss.cStr);
}
}
默认/赋值构造函数
String::String(const char * const p) {
if (p == NULL) {
cStr = NULL; len = 0;
} else {
len = strlen(p);
cStr = new char[len + 1];
strcpy(cStr, p);
}
}
错误函数:
void String::diskIn(std::ifstream &fin) {
String temp;
fin.read((char *)&temp.len, sizeof(int));
temp.cStr = new char[len + 1];
int i;
for (i = 0; i < temp.len; i++)
fin.get(temp.cStr[i]);
temp.cStr[i] = '\0';
*this = temp;
}
复制赋值运算符
String String::operator = (const String ss) {
if (cStr != NULL) {
delete[] cStr;
cStr = NULL;
len = 0;
}
if (ss.cStr != 0) {
len = ss.len;
cStr = new char[len + 1];
strcpy(cStr, ss.cStr);
}
return *this;
}
析构函数
String::~String() {
delete[] cStr;
}
int main() {
String s2;
std::ifstream ifile("document.txt");
s2.diskIn(ifile); //Error was thrown here
std::cout << s2.getString() << "\n";
ifile.close();
return EXIT_SUCCESS;
}
解决方案
推荐阅读
- ffmpeg - 使用 ffmpeg 将 rtsp 流式传输到 rtmp 时丢失数据包错误
- vb.net - 如何使用类似于 Spy++ 64 日志消息的 Windows API 在 VB.Net 中捕获另一个应用程序的消息
- javascript - 当实际上没有要添加的值时,向 Object 值添加值
- python - Pandas Dataframe - 按 Col A 分组并对每个组 Col C 求和
- jmeter - 基本 Jmeter 负载测试:10k 不同用户并发登录。所有 10k 用户都应该先在系统中注册吗?
- reactjs - React.default.memo 不是一个函数 (React-Native) wrapWithConnect
- python-3.x - CloudFormation 堆栈删除无法删除 VPC
- facebook - 使用 Firebase 动态链接分享到 Facebook 时无法预览
- javascript - 未捕获的 referenceError 变量未定义
- javascript - 使用三元运算符但不使用 if else 语句的代码