繁体   English   中英

c++ 程序与动态 memory 的问题,有 memory 泄漏,ZA8CFDE6331BD59EB66AC96F8911C4 指针的动态数组

[英]Problem with c++ program with dynamic memory, has memory leaks, dynamic array of object pointers

我正在编写一个用于向多边形 class 添加点的程序,这是下面的代码。 我得到 memory 泄漏并且完全迷失了。 非常感谢!

更新:也许有 memcpy 的替代品吗?

#include <iostream>
#include <cstring>
#include <cstdint>

struct Coordinate {
    int x, y;

    Coordinate () : x(), y() {}
    Coordinate (int _x, int _y) : x(_x), y(_y) {}
};

class Polygon {
    int points;
    Coordinate** coordinates;

public:

    Polygon (int _points) {
        points = _points;
        coordinates = new Coordinate*[points+1];
    }

    ~Polygon () {

        for (int i = 0; i <=points; i++){
            delete coordinates[i];
        }
        delete [] coordinates;

    }

    void putPoint (Coordinate ** pts) {
        for (int i = 0; i < points; i++) {
            memcpy(&coordinates[i], &pts[i%points], sizeof(coordinates[i]));
        }
    }

};

int main () {

    Coordinate q1 = {0,0};
    Coordinate q2 = {0,2};
    Coordinate q3 = {2,2};
    Coordinate q4 = {2,0};


    Coordinate* quadPts[4] = {&q1, &q2, &q3, &q4};
    Polygon * quad = new Polygon(4);

    quad->putPoint(quadPts);
}

错误信息

==20066==错误:LeakSanitizer:检测到 memory 泄漏

1 个对象中的 16 字节直接泄漏,分配自:#0 0x7fd18ba55947 in operator new(unsigned long) (/lib/x86_64-linux-gnu/libasan.so.5+0x10f947)

从以下位置分配的 1 个对象中 32 字节的间接泄漏:#0 0x7fd18ba55b47 in operator new[](unsigned long) (/lib/x86_64-linux-gnu/libasan.so.5+0x10fb47)

好的,所以,您的Coordinate结构不需要像那样动态分配。 它很小,可轻松复制,具有值语义,并且没有虚拟成员。 通过使用这些指针,您将一无所获。

其次,动态 arrays 使用起来很痛苦。 您应该始终使用容器,最好是std::vector ,因为它具有相同的一般特征。

最后,虽然memcpyCoordinate中工作得很好,因为它可以简单地复制,但在 C++ 中使用它来复制对象是个坏主意,因为当你将它用于比这更复杂的事情时,你最终会得到未定义的行为。 实际上, memcpy应该只用于字节缓冲区。

把所有这些放在一起,这是一个简化的版本:

#include <vector>

struct Coordinate {
    int x, y;

    Coordinate () : x(), y() {}
    Coordinate (int _x, int _y) : x(_x), y(_y) {}
};


int main () {    
    Coordinate q1 = {0,0};
    Coordinate q2 = {0,2};
    Coordinate q3 = {2,2};
    Coordinate q4 = {2,0};

    std::vector<Coordinate> quad = { q1, q2, q3, q4 };
}

而已。 当然,它并不完全相同:我摆脱了Polygon并直接使用了向量,因为您当前的用例不需要它。 如果需要,请随意将其包装成 class。

这里的重点是,您的大部分代码基本上都是在重新创建标准库设施,但效果不佳。 一旦你开始考虑已经可用的东西,很多复杂性就会消失。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM