1

I have made a header file which contains an array of a fixed size (17) but there is something fundamentally incorrect and I cannot find what.

ScreenArray.h

    class ScreenArray
    {
    public:
        ScreenArray();
        ~ScreenArray();
        unsigned long getColour(int arrayPointer);
        void setColour(int arrayPointer, unsigned long pixelColour);
    private:
        unsigned long pixelArray[17];
    };

ScreenArray.cpp

#include "PixelScreenArray.h"

ScreenArray::ScreenArray()
{

}

ScreenArray::~ScreenArray()
{
    delete[] pixelArray;
}

unsigned long ScreenArray::getColour(int arrayPointer)
{
    return pixelArray[arrayPointer];
}

void ScreenArray::setColour(int arrayPointer, unsigned long pixelColour)
{
    pixelArray[arrayPointer] = pixelColour;
}

Source.cpp

...
ScreenArray sA;
sA.setPixel(0, 3242);
...
Marco A.
  • 43,032
  • 26
  • 132
  • 246
Built on Sin
  • 351
  • 2
  • 6
  • 19

1 Answers1

1

If you didn't allocate the array with new[] you shouldn't delete[] it, this is wrong:

class ScreenArray
{
public:
    ScreenArray();
    ~ScreenArray() {
       delete[] pixelArray; // Nope
    }
private:
    unsigned long pixelArray[17];
};

the array is a member of the class and whether the entire object is allocated on the stack as you did:

ScreenArray sA;
sA.setPixel(0, 3242);

or allocated on the heap with a new ScreenArray();, you can't "just delete part of the object away".

In your specific case you're trying to free stack memory and that's UB

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246