动态数组的 C++ 内存泄漏

标签 c++ arrays dynamic memory-leaks

我不得不自己从头开始构建一个动态数组类,我还尝试用一个(set like)函数扩展它以将新元素添加到数组中,它编译得很好,但程序崩溃了,因为它有一些内存泄漏。

请尝试帮助我,我在学校有临时通知。

数组类

template <class T>
class Array
{
    int n; /// size
    T* data;
public:
    explicit Array(int n): n(n) { adat=new T[n]; }
    Array(const Array&);
    Array& operator=(const Array&);
    ~Array();

    T& operator[](int idx) { return data[idx]; }
    int size() { return n; }
    int lookfor(T);
    void add(T);
    void del();
};

定义

template <class T>
Array<T>::Array(const Array<T>& t)
{
    n=t.n;
    data=new T[n];
    for (int idx=0; idx<n; ++idx)
        data[idx]=t.data[idx];
}

/**
    Operator=
*/
template <class T>
Array<T>& Array<T>::operator=(const Array<T>& t)
{
    if (this==&t) return *this;
        delete[] data;

    n=t.n;
    data=new T[n];
    for (int idx = 0; idx < n; ++idx)
        data[idx]=t.data[idx];

    return *this;
}

/**
    dtor
*/
template <class T>
Array<T>::~Array()
{
    del();
}

这一定是错误的部分

template <class T>
int Array<T>::lookfor(T el)
{
    for(int idx = 0; idx < n; ++idx)
        if(data[idx] == el)
            return idx;
    return -1;
}

/**
    add
*/
template <class T>
void Array<T>::add(T el)
{
    if(lookfor(elem) != -1)
    {
        T* temp = new T[n + 1];

        for (int idx = 0; idx < n; ++idx)
            temp[idx]=data[idx];

        temp[n + 1] = el;

        del();
        data = temp;
        ++n;
    }
}

template <class T>
void Array<T>::del()
{
    for(int idx = 0; idx < n; ++idx)
        delete data[idx];

    delete[] data;
}

失败的代码:

Control ctrl;

ctrl.add(new Room());
ctrl.add(new Room());

Control 和 Room 都是数组的子类。喜欢控制:publicArray < Room* >

最佳答案

摆脱 del() 中删除所有 data[idx] 元素的循环。 data 不是指针数组,它是 T 类型的值数组,因此您无法删除它们。即使您制作了一个指针数组,这些指针也来自 add 的调用者,并且它们属于程序的那部分,而不是 Array 类。您也不想在向数组添加元素时删除所有旧指针,因为新的 data 数组仍包含这些指针。

对不是使用 new 创建的内容调用 delete 会导致未定义的行为,这可能会导致崩溃。

关于动态数组的 C++ 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37233066/

相关文章:

java - 在冒泡排序中按升序或降序排序

magento - 在 magento 中将动态价格从详细页面传递到购物车

无法跳出 "While"循环

c++ - 闪存驱动器损坏的文件系统上的文本文件恢复

php - "Notice: Undefined variable"、 "Notice: Undefined index"、 "Warning: Undefined array key"和 "Notice: Undefined offset"使用 PHP

c++ - 二叉搜索树中的插入错误

javascript - 什么是 Javascript 代码的 O(1) 空间复杂度以及示例

c - 函数内二维数组的动态分配(使用指针返回分配对象的地址)

c++ - 我可以在程序中定义的函数上使用 execvp() 吗?

c++ - 数据结构的时间复杂度