I've been trying to complete a class assignment but I keep getting an error that I can't seem to resolve. Debug Assertion failed I've narrowed the problem (I think) to the destructor. If I comment out the line delete[] english;
there is no error. I've tried reading through other threads, but they haven't helped solve this. Here are the three files in the project (I took out all the rest of the code because the error still occurs with just this):
Here is the header file:
//Dictionaty.h
#ifndef DICTIONARY_H
#define DICTIONARY_H
class Dictionary
{
public:
Dictionary();
~Dictionary();
void setEnglish(char*);
char* getEnglish();
private:
char *english;
};
#endif
Here is where the functions are:
//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
}
and this is the driver:
//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;
}
The problem is
Then the member varialbe
english
is assigned to the pointer decayed from arraytest
, which isn't dynamic allocated usingnew[]
and then can't bedelete[]
ed, but it's exactly what the destructor is trying to do. Therefore UB.According to the intent of your code, you should use
strcpy
orstrncpy
inDictionary::setEnglish
, don't assign the pointer directly.Other suggestions:
Consider about The Rule of Three, especially when you use raw pointers (such as
char*
).Use std::string instead of C-style strings (
char*
).