Search code examples
c++arraysmemory-leaksnew-operator

Allocating memory with the 'new[]' operator


I'm trying to do simple 3D graphics on a Arduino Due. Amongst others, I created a PointContainer class and a Vector3D class. I realized that I had a memory problem, because when I created an object with around 100 points, the Arduino sketch wouldn't work.

I used the suggested code on the arduino.cc forum to monitor memory usage.

This is a line of code in the setup() function of my Arduino sketch:

PointContainer pcSphere(84);

Before this line, the free memory is 55024 bytes and after it, it is 32480 bytes.

This is how the PointContainer and Vector3D classes are defined:

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)];
}

I know that I have to use delete to free memory after using new. But I use the vector data until the end of the program, so this is not a problem.

sizeof(Vector3D) is 16, I checked that. PointContainer pcSphere(84) should only allocate approx. 1344 bytes of memory, but right now, it allocates 22544 bytes. When I create the array directly, like Vector3D points[84] = {Vector3D(1,1,1,1),...}, it allocates the correct amount of 1344 bytes of memory.

I think I'm using the new operator the wrong way. But what is the correct way to dynamically create a simple array?


Solution

  • new T[n] allocates memory for n objects of type T (and constructs them), and not n bytes. Therefore, multiplication like this:

    new T[n*sizeof(T)]

    is wrong.