Pull Request: Fix memory leak in MjpegClass#2
Open
jkarsten wants to merge 3 commits into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
#Problem
Currently, MjpegClass::setup() allocates _read_buf with malloc(READ_BUFFER_SIZE) every time it is called, but never releases previously allocated memory.
When a MJPEG file is restarted in a loop, this leads to a gradual heap leak (≈1 KB per restart on ESP32). After ~200 restarts the device runs out of memory and crashes.
##Changes
Added cleanup in setup() to free(_read_buf) before allocating a new buffer.
Added a destructor ~MjpegClass() to ensure _read_buf is freed when the object is destroyed.
Changed return value of setup() to (_read_buf != nullptr) so it properly reports allocation failures.
##Modified code (excerpt):
bool setup(
Stream *input, uint8_t *mjpeg_buf, JPEG_DRAW_CALLBACK *pfnDraw, bool useBigEndian,
int x, int y, int widthLimit, int heightLimit)
{
_input = input;
_mjpeg_buf = mjpeg_buf;
_pfnDraw = pfnDraw;
_useBigEndian = useBigEndian;
_x = x;
_y = y;
_widthLimit = widthLimit;
_heightLimit = heightLimit;
_inputindex = 0;
}
// new destructor
~MjpegClass() {
if (_read_buf) {
free(_read_buf);
_read_buf = nullptr;
}
}
##Result
Heap usage on ESP32 remains stable across hundreds of looped video restarts.
No crashes due to gradual memory exhaustion.