【发布时间】:2013-10-26 04:03:29
【问题描述】:
所以,我在我正在处理的有序列表类的 Expand 方法中遇到堆损坏错误。当客户端尝试将新项目插入()到列表中时,会调用 expand 方法,并且当前数组中没有剩余空间。当我取出删除行时,程序运行良好,但我知道每次扩展时我都有一个无法访问的对象。但是,当我放入删除行时,程序会在运行时爆炸。
此外,这只发生在我的 Expand() 方法中。它没有在我的 Contract() 方法中执行此操作,每次从列表中删除使列表元素的数量低于当前可用总空间的 1/4 时都会调用该方法,它将大小减少一半。我可以毫无问题地删除此方法中的旧列表。
GetListPtr()、SetListPtr() 和 GetLength() 都继承自一个 ListClass 对象,我以头文件和对象代码的形式收到该对象,所以我不确定它们究竟是如何工作的。 ItemType 是一个结构体,只包含一个整数字段,key。
我已经在这里阅读了许多问题,但没有发现任何似乎对我的情况有任何帮助的问题。
void OrdListClass::Expand()
{
ItemType* newList = new ItemType[size * 2];
ItemType* temp = GetListPtr();
size = size * 2;
// Copy the current list to the new list.
for(int i = 0; i < GetLength(); i++)
newList[i] = temp[i];
// Point to the new list.
SetListPtr(newList);
// Delete the old list
delete temp; <-- This line
// Reset the pointers
temp = nullptr;
newList = nullptr;
}
void OrdListClass::Contract()
{
ItemType* newList = new ItemType[size / 2];
ItemType* temp = GetListPtr();
size = size / 2;
// Copy the old list into the new one
for(int i = 0; i < GetLength(); i++)
newList[i] = temp[i];
// Set the list pointer to point to the new list
SetListPtr(newList);
// Delete the old list
delete temp;
temp = nullptr;
newList = nullptr;
}
再次感谢您阅读本文,感谢任何和所有帮助。
【问题讨论】:
-
GetLength()是否使用size? -
另外,如果你使用
new[]进行分配,那么你需要使用delete[]。 -
如果不是很明显,
GetListPtr()和GetLength()对于此功能的工作方式至关重要,如果您决定不 包括它们是.. 不方便。尤其是考虑到忍者先生仍未回答的问题。 -
抱歉,回复太迟了,我整晚都在为这个程序工作,最后在我看到任何回复之前就睡着了。关于 GetListPtr(),它与 SetListPtr() 和 GetLength() 一起从 ListClass 对象继承,该对象以头文件和对象代码的形式提供给我,所以我不知道究竟是如何获取/SetListPtr() 工作,但我知道 GetLength() 返回列表中的当前元素数。 size 变量保存数组的当前大小,或者它可以容纳的最大元素。
-
因此,例如,您不知道
SetListPtr是否为您删除了旧指针。似乎是时候与您获得此代码的人谈谈了。
标签: c++ visual-studio-2010 visual-c++ heap-memory