使用"删除"运算符清理内存时出现"调试断言失败"错误
'Debug Assertion Failed' Error when cleaning memory using 'delete' operator
我已经尝试了所有方法,但代码不工作,我不明白为什么。
我有两个类。这个是基类:
class Vegetables
{
private:
char *nameStr;
char *countrySrc;
int seasonRd;
public:
Vegetables()
{
cout << "Default constructor for Vegetables" << endl;
nameStr = new char[20];
nameStr = "Unknown";
countrySrc = new char[20];
countrySrc = "Unknown";
seasonRd = -1;
}
virtual ~Vegetables()
{
delete[]nameStr; //Here happens the error (_crtisvalidheappointer(block))
delete[]countrySrc;
cout << "Destructor for Vegetables" << endl;
}
};
继承了"inherited Unit"类:
class InhUnit : public Vegetables
{
private:
Delivery delivery_;
Vegetables vegetables;
int quantity;
int price;
int delivPrice;
public:
InhUnit() :Vegetables(),delivery_(OwnCosts), vegetables(), quantity(-1), price(-1), delivPrice(-1)
{
cout << "Default constructor for Inherited Unit" << endl;
}
~InhUnit()
{
cout << "Destructor for Inherited Unit" << endl;
}
};
弹出这个错误的原因是什么?
这不是你复制字符串的方式,使用strcpy
代替
Vegetables()
{
cout << "Default constructor for Vegetables" << endl;
nameStr = new char[20];
strcpy(nameStr, "Unknown");
countrySrc = new char[20];
strcpy(countrySrc, "Unknown");
seasonRd = -1;
}
你所做的是分配一些内存并将其分配给指针。然后在下一行,您将指针赋值给指向字符串的指针,而不是将字符串复制到您分配的内存中。
当你调用delete[]
时,因为指针没有指向你分配的内存,你得到了一个错误。
您应该使用像std::string这样的字符串类来避免指针问题。
修改代码
class Vegetables {
private:
std::string nameStr; // Use std::string instead of C-style string
std::string countrySrc;
int seasonRd;
public:
// Use constructor initialization list
Vegetables() : nameStr("Unknown"), countrySrc("Unknown"), seasonRd(-1) {
cout << "Default constructor for Vegetables" << endl;
}
virtual ~Vegetables() {
cout << "Destructor for Vegetables" << endl;
}
};
相关文章:
- 从 exe 文件 (Visual Studio ) 启动时调试断言失败
- 使用扫描的调试断言失败
- 图片不显示,关闭时出错 --> 调试断言失败!表达式:is_block_type_valid(标头>_block_use)
- C++ 调试断言失败 - 矢量下标超出视觉工作室的范围
- 调试断言失败的缓冲区!=nullptr
- 获取有关调试断言失败的错误:表达式:"(_Ptr_user &(_BIG_ALLOCATION_ALIGNMENT -1)) == 0" &&0
- 在Win10上使用带有Qt5的OpenCV3.0,调试断言失败
- C++,弹出调试断言失败窗口,我得到矢量迭代器不兼容的错误运行时
- C++ 调试断言失败,无效的空指针
- 如何在 Linux 上强制执行矢量下标超出范围的调试断言
- 调试断言仅在某些情况下失败?C++
- 调试断言失败
- 映射/集迭代器不可取消引用 (C++) - 调试断言失败
- std::vector<std::vector<int>>:调试断言失败。C++矢量下标超出范围保留内存
- 使用 Microsoft VS 编写程序C++,但我在这里收到调试断言消息.它可以在 cpp.sh 上运行,repl.i
- 字符串抛出矢量下标调试断言
- 使用调试断言时避免 ODR 冲突
- MFC DDX_RADIO会导致调用dodataexchange(dlgdata.cpp行286)时导致调试断言失败
- 无法在谷歌测试中捕获调试断言(死亡测试不满足它)
- 调试断言失败的矢量下标超出C 范围