繁体   English   中英

为什么取消分配内存会导致崩溃?

[英]Why does deallocating memory cause a crash?

我为此结构分配了一些内存( 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[]导致程序冻结?

wordListclass 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;
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM