【发布时间】:2013-10-27 20:11:23
【问题描述】:
我为这个结构分配了一些内存(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;
}
【问题讨论】:
-
代码是
wordList是成员的更大类的一部分,对吗?你能显示所有的构造函数和析构函数吗? -
wordList必须指向一个 有效 以前的数组分配,或者它必须是nullptr。其他任何东西都是未定义的行为。 -
听起来你不小心写的比某处允许的多,所以我们需要更多的上下文来找出问题所在
-
@WhozCraig 刚刚得到 OP 更新的确认 :) OP:阅读我关于三/五规则的其他评论中的链接并实施适当的复制器。
-
@user2925882 会这样做。有很多方法可以解决这个问题,包括使用标准容器工作默认复制(我会这样做)。 IE。
std::vector<Word>这样,new和delete就不需要在您的源代码中了。无论如何,请参阅丹尼尔的链接。并且here is another for you 如果再次出现通过新/删除来手动管理自己的内存的愿望。
标签: c++ memory memory-management struct