diff --git a/32blit/graphics/surface.cpp b/32blit/graphics/surface.cpp index 49b90aa71..cc8a0a307 100644 --- a/32blit/graphics/surface.cpp +++ b/32blit/graphics/surface.cpp @@ -51,6 +51,12 @@ namespace blit { Surface::Surface(uint8_t *data, const PixelFormat &format, const Size &bounds) : data(data), bounds(bounds), format(format) { init(); } + + Surface::~Surface() + { + if (_bNewData) delete[] data; + if (_bNewPalette) delete[] palette; + } /** * Loads a packed or raw image asset into a `Surface` @@ -641,6 +647,7 @@ namespace blit { if (format == PixelFormat::P || !is_raw) { // load palette ret->palette = new Pen[256]; + ret->_bNewPalette = true; file.read(offset, palette_entry_count * 4, (char *)ret->palette); offset += palette_entry_count * 4; } @@ -650,7 +657,10 @@ namespace blit { ret->data = (uint8_t *)file.get_ptr() + offset; else { if(!ret->data) - ret->data = new uint8_t[needed_size]; + { + ret->data = new uint8_t[needed_size]; + ret->_bNewData = true; + } file.read(offset, image.width * image.height * pixel_format_stride[image.format], (char *)ret->data); } @@ -658,7 +668,10 @@ namespace blit { } if(!ret->data) - ret->data = new uint8_t[needed_size]; + { + ret->data = new uint8_t[needed_size]; + ret->_bNewData = true; + } // avoid allocating if in flash const uint8_t *image_data, *end; @@ -755,6 +768,7 @@ namespace blit { // unpacked, no longer needed delete[] ret->palette; ret->palette = nullptr; + ret->_bNewPalette = false; } if (!file.get_ptr()) { diff --git a/32blit/graphics/surface.hpp b/32blit/graphics/surface.hpp index 1d5b1ad5a..efabe67dc 100644 --- a/32blit/graphics/surface.hpp +++ b/32blit/graphics/surface.hpp @@ -119,6 +119,9 @@ namespace blit { public: Surface(uint8_t *data, const PixelFormat &format, const Size &bounds); + ~Surface(); + bool _bNewData{false}; + bool _bNewPalette{false}; static Surface *load(const std::string &filename, uint8_t *data, size_t data_size); static Surface *load(const std::string &filename) {return load(filename, nullptr, 0);};