【问题标题】:Allocating memory with the 'new[]' operator使用 'new[]' 操作符分配内存
【发布时间】:2018-02-04 00:13:34
【问题描述】:

我正在尝试在 Arduino Due 上制作简单的 3D 图形。其中,我创建了一个PointContainer 类和一个Vector3D 类。我意识到我有一个内存问题,因为当我创建一个大约 100 个点的对象时,Arduino 草图无法工作。

我使用arduino.cc 论坛上的建议代码来监控内存使用情况。

这是我的 Arduino 草图的setup() 函数中的一行代码:

PointContainer pcSphere(84);

在这一行之前,空闲内存为 55024 字节,之后为 32480 字节。

PointContainerVector3D 类是这样定义的:

class Vector3D {
    public:
        Vector3D(int16_t x, int16_t y, int16_t z, int16_t w);

        int32_t data[4] = {0, 0, 0, 128};
};

Vector3D::Vector3D(int16_t x, int16_t y, int16_t z, int16_t w){
    data[0] = x<<7;
    data[1] = y<<7;
    data[2] = z<<7;
    data[3] = w<<7;
}

class PointContainer {
    public:
        PointContainer(uint8_t pointCount);

        Vector3D *points;

    private:
        uint8_t pointCount;
};

PointContainer::PointContainer(uint8_t pointCount) {
    this->pointCount = pointCount;
    points = new Vector3D [pointCount * sizeof(Vector3D)];
}

我知道在使用new 之后我必须使用delete 来释放内存。但是我一直使用矢量数据直到程序结束,所以这不是问题。

sizeof(Vector3D) 是 16,我查过了。 PointContainer pcSphere(84) 应该只分配大约。 1344 字节的内存,但现在,它分配了 22544 字节。当我直接创建数组时,比如Vector3D points[84] = {Vector3D(1,1,1,1),...},它会分配正确数量的 1344 字节内存。

我认为我以错误的方式使用了 new 运算符。但是动态创建简单数组的正确方法是什么?

【问题讨论】:

  • T* p = new T[123]; 你需要delete[]new[]T 是你的类型。
  • @Ron 请在写之前阅读。
  • 我做到了。你的问题不是:但是动态创建简单数组的正确方法是什么?
  • 我遇到的问题是它在一次调用中分配了太多内存,我想知道如何分配适量的内存。
  • 你的代码因为这条线而无法编译 points = new Vector3D[pointCount * sizeof(Vector3D)]; 它调用了 Vector3D 你没有在你的例子中提供的默认构造函数。

标签: c++ arrays memory-leaks new-operator


【解决方案1】:

new T[n]n 类型为T 的对象分配内存(并构造它们),而不是n 字节。因此,像这样的乘法:

new T[n*sizeof(T)]

错了。

【讨论】:

  • 多余的意思不是没有害处吗?这完全是错误的。
  • @manni66 我不明白这个词是如何暗示的,但为了清楚起见,我将编辑答案。
猜你喜欢
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 2010-10-10
  • 1970-01-01
  • 1970-01-01
  • 2011-06-17
  • 1970-01-01
相关资源
最近更新 更多