c++ - 错误调试断言失败 - 删除动态分配的数组时

标签 c++ memory-management delete-operator

我一直在尝试完成类作业,但我总是收到一个我似乎无法解决的错误。 Debug Assertion failed我已经将问题(我认为)缩小到析构函数。如果我注释掉 delete[] english; 行,则没有错误。我试过阅读其他线程,但他们没有帮助解决这个问题。这是项目中的三个文件(我把剩下的所有代码都拿出来了,因为就这样还是会报错):

这是头文件:

//Dictionaty.h
#ifndef DICTIONARY_H
#define DICTIONARY_H

class Dictionary
{
public:
    Dictionary();
    ~Dictionary();

   void setEnglish(char*);
   char* getEnglish();


private:
    char *english;

};

#endif

这里是函数所在的地方:

//dictionary.cpp
#include <iostream>
#include "Dictionary.h"

using namespace std;

Dictionary::Dictionary()
{
    english = new char[20];


    strcpy(english, " ");
    //strcpy(french, " ");
}

Dictionary::~Dictionary()
{
    delete[] english; // problem is here (i think)

}

void Dictionary::setEnglish(char *eng)
{
    english = eng;
    cout << "the value of english in \"setEnglish()\" is: " << english << endl; //db
}

这是驱动程序:

//dictionaryDrv.cpp
#include <iostream>
#include "Dictionary.h"

using namespace std;

int main()
{
    Dictionary words[30];

    //readIn(words);
    char test[5] = "test";
    words[0].setEnglish(test);


    system("pause");
    return 0;
}

最佳答案

问题是

char test[5] = "test";
words[0].setEnglish(test);

然后成员 varialbe english 被分配给从数组 test 衰减的指针,它不是使用 new[] 动态分配的,并且then 不能被 delete[]ed,但这正是析构函数试图做的。因此 UB。

根据你的代码意图,你应该在Dictionary::setEnglish中使用strcpystrncpy,不要分配指针直接。

其他建议:

  1. 考虑 The Rule of Three ,尤其是当您使用原始指针(例如 char*)时。

  2. 使用 std::string而不是 C 风格的字符串 (char*)。

关于c++ - 错误调试断言失败 - 删除动态分配的数组时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41205206/

相关文章:

python - 无法将长整数从嵌入式 Python 返回到 C++

c++ - 如何对 std::tuple 中的每个元素应用 constexpr 函数?

c - C 中的 free 和 C++ 中的 delete 之间的区别?

删除对象时出现 C++ 断言错误

c++ - 如果 A 有析构函数,什么时候 std::unique_ptr<A> 需要一个特殊的删除器?

C++ 结构体与类在内存方面的比较

c++ - 为什么我们不能通过值传递数组来函数?

objective-c - 返回指向不同对象的指针的方法是否会自动分配和初始化其他对象?

c# - 未执行 C# 中的垃圾收集。为什么?

javascript - 奇怪的内存行为