From 89ec43b8518f50e6025a14a33cab94fdefa2a056 Mon Sep 17 00:00:00 2001 From: LordGrey <48840279+Lord-Grey@users.noreply.github.com> Date: Fri, 29 Dec 2023 18:13:11 +0100 Subject: [PATCH] Fix memory leak caused by wrong buffer allocation --- include/utils/ImageData.h | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/include/utils/ImageData.h b/include/utils/ImageData.h index e850fba3..7a7a1808 100644 --- a/include/utils/ImageData.h +++ b/include/utils/ImageData.h @@ -1,12 +1,9 @@ #pragma once // STL includes -#include #include #include #include -#include -#include #include // QT includes @@ -112,14 +109,19 @@ public: void resize(unsigned width, unsigned height) { if (width == _width && height == _height) - return; - - if ((width * height) > unsigned((_width * _height))) { - delete[] _pixels; - _pixels = new Pixel_T[width*height + 1]; + return; } + // Allocate a new buffer without initializing the content + Pixel_T* newPixels = new Pixel_T[static_cast(width) * static_cast(height)]; + + // Release the old buffer without copying data + delete[] _pixels; + + // Update the pointer to the new buffer + _pixels = newPixels; + _width = width; _height = height; } @@ -137,7 +139,9 @@ public: void toRgb(ImageData& image) const { if (image.width() != _width || image.height() != _height) + { image.resize(_width, _height); + } const unsigned imageSize = _width * _height; @@ -159,11 +163,19 @@ public: { _width = 1; _height = 1; + + // Allocate a new buffer without initializing the content + Pixel_T* newPixels = new Pixel_T[static_cast(_width) * static_cast(_height)]; + + // Release the old buffer without copying data delete[] _pixels; - _pixels = new Pixel_T[2]; + + // Update the pointer to the new buffer + _pixels = newPixels; } - memset(_pixels, 0, static_cast(_width) * static_cast(_height) * sizeof(Pixel_T)); + // Set the single pixel to the default background + _pixels[0] = Pixel_T(); } private: @@ -172,7 +184,6 @@ private: return y * _width + x; } -private: /// The width of the image unsigned _width; /// The height of the image