Issues freeing image data from stb_image in wrapper class

1.1k views Asked by At

I am writing an Image class for a project using the raw data from stb_image. In the destructor for this class I am freeing the pointer to the image data to avoid memory leaks. However, when the destructor is called and the data is freed, I get an access violation.

The header of image:

class Image {
    unsigned char* pixelData;
    public:
        int nCols, nRows, nChannels;
        Image(const char* filepath);
        Image(unsigned char* data, int nCols, int nRows, int nChannels);
        Image();
        ~Image();
        Image getBlock(int startX, int startY, int blockSize);
        std::vector<unsigned char> getPixel(int x, int y);
        void writeImage(const char* filepath);

};

The constructor and destructor of Image:

#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION

#include "stb_image.h"
#include "stb_image_write.h"
#include "image.hpp"

Image::Image(const char* filepath) {
    pixelData = stbi_load(filepath, &nCols, &nRows, &nChannels, 0);
    assert(nCols > 0 && nRows > 0 && nChannels > 0);
    std::cout << "Image width: " << nCols << "\nImage height: " << nRows << "\nNumber of channels: " << nChannels << "\n";
}

Image::~Image() {
    stbi_image_free(this->pixelData);
}

Minimum reproducable example:

int main() {
    Image image;
    image = Image("./textures/fire.jpg");
}
1

There are 1 answers

0
panky On BEST ANSWER

Default copy constructor would lead to double free. There are two ways to fix it -

  1. You can wrap the resource with unique_ptr having custom deleter and this would make the class move-only anyways.
  2. Or, make it non-copyable explicitly.