Fix memory leak caused by wrong buffer allocation

This commit is contained in:
LordGrey
2023-12-29 18:13:11 +01:00
parent fcee3d0cbf
commit 89ec43b851

View File

@@ -1,12 +1,9 @@
#pragma once #pragma once
// STL includes // STL includes
#include <vector>
#include <cstdint> #include <cstdint>
#include <cstring> #include <cstring>
#include <algorithm> #include <algorithm>
#include <cassert>
#include <type_traits>
#include <utils/ColorRgb.h> #include <utils/ColorRgb.h>
// QT includes // QT includes
@@ -112,14 +109,19 @@ public:
void resize(unsigned width, unsigned height) void resize(unsigned width, unsigned height)
{ {
if (width == _width && height == _height) if (width == _width && height == _height)
return;
if ((width * height) > unsigned((_width * _height)))
{ {
delete[] _pixels; return;
_pixels = new Pixel_T[width*height + 1];
} }
// Allocate a new buffer without initializing the content
Pixel_T* newPixels = new Pixel_T[static_cast<size_t>(width) * static_cast<size_t>(height)];
// Release the old buffer without copying data
delete[] _pixels;
// Update the pointer to the new buffer
_pixels = newPixels;
_width = width; _width = width;
_height = height; _height = height;
} }
@@ -137,7 +139,9 @@ public:
void toRgb(ImageData<ColorRgb>& image) const void toRgb(ImageData<ColorRgb>& image) const
{ {
if (image.width() != _width || image.height() != _height) if (image.width() != _width || image.height() != _height)
{
image.resize(_width, _height); image.resize(_width, _height);
}
const unsigned imageSize = _width * _height; const unsigned imageSize = _width * _height;
@@ -159,11 +163,19 @@ public:
{ {
_width = 1; _width = 1;
_height = 1; _height = 1;
// Allocate a new buffer without initializing the content
Pixel_T* newPixels = new Pixel_T[static_cast<size_t>(_width) * static_cast<size_t>(_height)];
// Release the old buffer without copying data
delete[] _pixels; delete[] _pixels;
_pixels = new Pixel_T[2];
// Update the pointer to the new buffer
_pixels = newPixels;
} }
memset(_pixels, 0, static_cast<unsigned long>(_width) * static_cast<unsigned long>(_height) * sizeof(Pixel_T)); // Set the single pixel to the default background
_pixels[0] = Pixel_T();
} }
private: private:
@@ -172,7 +184,6 @@ private:
return y * _width + x; return y * _width + x;
} }
private:
/// The width of the image /// The width of the image
unsigned _width; unsigned _width;
/// The height of the image /// The height of the image