1

Word * wordList我为这个结构分配了一些内存( ):

    struct Word{
            int occurrences;
            std::string wrd;
    };

通过写作:

        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是调用这段代码之前和之后 wordList 的大小,wrd是传递给方法的字符串。运行此代码以在wordList.

我的问题是,当delete[]被调用时,程序停止工作。我试着用delete看看会发生什么,据我所知,该程序运行良好。发生了什么,为什么会delete[]导致我的程序冻结?

wordList是以下成员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);
    };

与构造函数:

    WordsOfLength::WordsOfLength(){
        numWords = 0;
        wordList = NULL;
    }

和析构函数:

    WordsOfLength::~WordsOfLength(){
        delete[] wordList;
        wordList = 0;
    }
4

1 回答 1

0

如果您在有问题的行之前没有分配wordList任何地方,那么您正在尝试释放未分配的内存。

于 2013-10-27T20:13:48.607 回答