我试图动态增加数组的容量,但是在运行valgrind时,我总是遇到内存泄漏。这是我正在运行的代码(它没有任何错误,不应该是问题所在):
//My struct
struct ArrayList{
int size; //amount of items in a array
int capacity; //the capacity of an array
int* items; //the array itself
};
//Dynamically create an array
ArrayList* createList(int m){
ArrayList* n = new ArrayList;
n->size = 0;
n->capacity = m;
n->items = new int[n->capacity];
return n ;
}
//Destroy an array
void destroyList(ArrayList* List){
delete[] List->items;
delete List;
}
使容量加倍的代码(我在那里得到内存泄漏):
// double the capacity of an array by dynamically creating a new one and transfering the old values to it
void doubleCapacity(ArrayList* List){
// save everything
int saved_size = List->size;
int saved_capacity = List->capacity;
int* saved_items = new int[List->size];
for (int i = 0 ; i < List->size;i++){
saved_items[i] = List->items[i];
}
// load everything
destroyList(List);
List->size = saved_size;
List->capacity = saved_capacity*2;
List->items = new int[List->capacity];
for (int i = 0; i < List->size; i++){
List->items[i] = saved_items[i];
}
delete[] saved_items;
}
我主要测试代码的双倍容量。
int main() {
// Run tests
ArrayList* l = createList(4);
l->size++;
l->items[0] = 1;
cout << l->size << endl;
cout << l->capacity << endl;
cout << l->items[0] << endl;
doubleCapacity(l);
cout << l->size << endl;
cout << l->capacity << endl;
cout << l->items[0] << endl;
destroyList(l);
return 0;
}
1条答案
按热度按时间ia2d9nvy1#
您的
doubleCapacity()
函数实现完全错误。它创建一个原始
size
的临时数组,只是为了保存当前items
的一个 * 冗余 * 副本。然后它创建一个所需capacity
的新数组,并将临时项复制到其中。你根本不需要那个临时数组,你可以直接将原始项复制到最终数组中。更重要的是,您正在销毁
ArrayList
对象本身,因此在它被销毁后对其成员的任何访问都是 undefined behavior。请尝试以下内容: