C++中无法消除内存泄漏

bxpogfeg  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(216)

我试图动态增加数组的容量,但是在运行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;
}
ia2d9nvy

ia2d9nvy1#

您的doubleCapacity()函数实现完全错误。
它创建一个原始size的临时数组,只是为了保存当前items的一个 * 冗余 * 副本。然后它创建一个所需capacity的新数组,并将临时项复制到其中。你根本不需要那个临时数组,你可以直接将原始项复制到最终数组中。
更重要的是,您正在销毁ArrayList对象本身,因此在它被销毁后对其成员的任何访问都是 undefined behavior
请尝试以下内容:

void doubleCapacity(ArrayList* List){   
    if (List->capacity > (std::numeric_limits<int>::max() / 2))
        throw std::overflow_error("capacity is too high to double");
    int new_capacity = List->capacity * 2;
    int* new_items = new int[new_capacity];
    for (int i = 0; i < List->size; i++){
        new_items[i] = List->items[i];
    }
    delete[] List->Items;
    List->items = new_items;
    List->capacity = new_capacity;
}

相关问题