Is it bad practice to reinitialize a pointer?

I have an Image class and initially I don't know the dimensions of the image, so I just initialize the pointer data_

as an array of size 0. Later, when I find information about the image, I reinitialize data_

for the new size. Will this create any memory problems? and is there a cleaner way to do this?

Below is the class I wrote:

class Image
{
private:
    int numRows_, numCols_;
    unsigned char* data_;
public:
    Image() : numRows_(0), numCols_(0), data_(new unsigned char[0])
    {}
    void setData(int r, int c, unsigned char* data)
    {
        this->numRows_ = r;
        this->numCols_ = c;
        this->data_ = new unsigned char[r*c];
        for (int i = 0; i < r*c; i++)
        {
            this->data_[i] = data[i];
        }
    }
    int rows();
    int cols();
    unsigned char* data();
    ~Image();
};

      

Thank you in advance

+3


source to share


2 answers


It will actually leak memory. The call new

allocates memory for the array even if it is empty . Once you reassign data_

, the previous array is leaked and can no longer be freed.

You can either make sure that you have delete[]

any new[]

you have selected, or just do not give out an empty array and instead set data_

in nullptr

, as long as you do not have the relevant data for use.

An even better idea is to not allow the creation of an object in an invalid state, require the data in the constructor - see RAII :



In RAII, resource storage is a class invariant and is tied to the lifetime of an object: resource allocation (or acquisition) is performed during object creation (in particular initialization), by the constructor, while resource release (release) is performed during object destruction (in particular, finalization) by a destructor.

If you choose to keep setData

, then as pointed out in the comments, you should also make sure the delete[]

existing data is in setData

before reassigning data_

if the method is called more than once.

+7


source


I think a cleaner way to do this would be using a vector:



std::vector<unsigned  char> v; // vector with size 0
v.resize(r*c);                 // after size is known, just resize

      

+3


source







All Articles