我一直在尝试完成类作业,但我总是收到一个我似乎无法解决的错误。 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
中使用strcpy
或strncpy
,不要分配指针直接。
其他建议:
考虑 The Rule of Three ,尤其是当您使用原始指针(例如
char*
)时。使用 std::string而不是 C 风格的字符串 (
char*
)。
关于c++ - 错误调试断言失败 - 删除动态分配的数组时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41205206/