c++ - 由于 new() 或 malloc 导致内存泄漏

标签 c++ memory-leaks

我正在尝试实现通常连续动态数组的替代方案,其中我使用指针 vector ,每个指针都指向一个恒定大小的数组,将其称为 XVector。

对于一定的输入限制(比如 150 个元素),它工作得很好,但超出这个限制,它就会开始抛出异常。

我尝试使用“新建和删除”而不是“malloc 和 free”,它确实增加了限制 - 比如说大约 1200 个元素 - 但仍然存在同样的问题。

我正在使用 C++。

这是我的主程序:

XVector<int> xv;

for(int i=0;i<1210;i++){
    int temp = rand()%100;
    xv.pushBack(temp);
}


for(int i=0;i<xv.size();i++){
    cout<<xv.getValue(i)<<" ";
}

cout<<"\n\n"<<xv.capacity();
return 0;

这是 XVector(D 头文件的类:

private:
    const int b = 10;
    vector<T*> arr;
    int currentIndex;
    int maxSize;


protected:
    void expand(){
        T* temp = new T[b];
        arr.push_back(temp);
        maxSize+=(b);

    }

    void shrink(){
        delete[] arr[arr.size()-1];
        arr[arr.size()-1] = NULL;
        arr.pop_back();
        maxSize-=(b);
    }

    int ceil(float num) {
        int inum = (int)num;
        if (num == (float)inum) {
            return inum;
        }
        return inum + 1;
    }

    pair<int,int> position(int index){
        pair<int,int> pos;
        float result = ((float)index/b);
        pos.first = result; //Row #
        pos.second = ceil((result - pos.first)*b); //Exact cell in the row
        return pos;
    }



    public:

    XVector(){
        currentIndex=0;
        maxSize=b;
        arr.reserve(120);
        arr.push_back(new T[b]);
    }

    void pushBack(T value){
        if(currentIndex>=maxSize-1){expand();}
        pair<int,int> indeces = position(currentIndex);
        arr[indeces.first][indeces.second]=value;
        currentIndex++;
    }

    void popBack(){
        currentIndex--;
        if(maxSize>=currentIndex+(2*b)){shrink();}
    }

    T getValue(int index){
        pair<int,int> indeces = position(index);
        return arr[indeces.first][indeces.second];
    }

    void setValue(int index,T value){
        pair<int,int> indeces = position(index);
        arr[indeces.first][indeces.second] = value;
    }

    int capacity(){
        return maxSize;
    }

    int size(){
        return currentIndex;
    }

    bool empty(){
        return currentIndex==0?true:false;
    }

PS:我尝试使用Valgrind,但未能找出确切的问题。

最佳答案

您的程序会泄漏内存,因为您从未在析构函数中释放指针。您必须实现析构函数来解决内存泄漏问题(除了移动构造函数、复制构造函数、赋值复制和赋值移动之外)。

除了v​​algrind之外,您还可以使用ASAN它具有更好的输出并且运行速度更快。

关于c++ - 由于 new() 或 malloc 导致内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48811149/

相关文章:

ruby - 当最后一个引用超出范围时,为什么我的 Ruby 对象没有被删除?

cocoa - CGContextDrawImage 吃掉我的内存,有内存泄漏吗?

c++ - 用于 Visual Studio 2005 和 Visual Studio 2008 的诺基亚 QT 4

c++ - 在 C++ 中返回两个创建的数组

java - 将 QByteArray 反序列化为 Java 数据类型

c++ - 如何使用消息正确创建自定义异常?

jquery - 为什么jquery泄漏内存如此严重?

ios - 尽管不使用 Core Plot,但核心动画无法分配字节

c++ - 在函数中声明非指针变量是内存泄漏吗?

c++ - 链表实现错误