I allocated some memory (Word * wordList
) for this struct:
struct Word{
int occurrences;
std::string wrd;
};
by writing:
Word * tempList = new Word[numWords + 1];
for(int i = 0; i < numWords; i++){
tempList[i] = wordList[i];
}
delete[] wordList;
wordList = tempList;
tempList = 0;
Word currWord = {1, wrd};
wordList[numWords] = currWord;
numWords++;
numWords
is the size of wordList before and after this bit of code is called and wrd
is a string passed into the method. This code runs to add a word when it isn't already present in wordList
.
My problem is that when delete[]
is called, the program stops working. I tried using delete
to see what would happen and the program worked fine as far as I could tell. What is going on and why does delete[]
cause my program to freeze?
wordList
is a member of class WordsOfLength
:
class WordsOfLength{
private:
int numWords;
Word * wordList;
public:
WordsOfLength();
WordsOfLength(int nNumWords, Word* nWordList);
~WordsOfLength();
void addWord(std::string wrd);
std::string getWord(int frequency);
friend void WordData::writeWordData(const char* fileName);
friend void WordData::setWordData(const char* fileName);
};
with constructor:
WordsOfLength::WordsOfLength(){
numWords = 0;
wordList = NULL;
}
and destructor:
WordsOfLength::~WordsOfLength(){
delete[] wordList;
wordList = 0;
}