【发布时间】:2019-12-16 00:04:49
【问题描述】:
我为教育目的实现了一个 ArrayList 类,但是在我的 expand() 方法中删除数组时遇到了内存错误。
这是我的课程和所有重要的方法:
//create array with default size 2
template<class T>
ArrayList<T>::ArrayList(){
realSize = 2;
count = 0;
data = new T[realSize];
}
//destructor
template<class T>
ArrayList<T>::~ArrayList() {
delete []data;
}
//adds value to end of list
template<class T>
void ArrayList<T>::add(T val) {
//if reached end of array, expand array
if (count >= realSize)
expand();
data[count] = val;
count++;
}
//inserts value at index
template<class T>
void ArrayList<T>::insert(T val, int index) {
if (!isValid(index)) return;
//if index is greater than current size, expand
while (index >= realSize || count >= realSize) {
expand();
}
//shift values before index
for (int i = count; i >= index; i--) {
T val = data[i];
data[i + 1] = data[i];
}
data[index] = val;
count++;
}
//return value at index
template<class T>
T ArrayList<T>::get(int index) {
if (!isValid(index)) return 0;
return data[index];
}
template<class T>
int ArrayList<T>::size() {
return count;
}
template<class T>
void ArrayList<T>::expand() {
//double array size
realSize = realSize * 2;
T* newData = new T[realSize];
//replace data
for (int i = 0; i < count; i++) {
newData[i] = data[i];
}
delete[]data; //<--ERROR OCCURS HERE
data = newData;
}
这里是一些会导致错误的代码
ArrayList<int>* list = new ArrayList<int>();
list->add(1);
list->add(5);
list->insert(2, 1);
list->insert(3, 2);
list->insert(4, 3); //<---ERROR OCCURS HERE
错误是一个显示为
的消息框调试错误!
程序: ...ommunity\Common7\IDE\Extensions\TestPlatorm\testhost.x86.exe
检测到堆损坏:在 0x05D69BC0 的正常块 (#296) 之后
CRT 检测到应用程序在堆缓冲区结束后写入内存。
为什么在调用expand方法时偶尔会报错?据我所知,当调用 expand() 时,数组的顺序是预期的(在我的示例中,它是 {1, 2, 3, 5})。
【问题讨论】:
-
您的
expand函数存在不相关但更进一步的问题,例如在调用new[]之前调整成员变量。如果new[]抛出异常,则您现在有一个具有错误值的对象。 -
感谢您的评论。我将翻转调整和内存分配以解决故障。
标签: c++ arrays memory allocation