Describe the bug
In pstget(), when fopen() succeeds but malloc() for the read buffer subsequently fails, the file handle is not closed before returning. This leaks a FILE* and its underlying file descriptor each time it occurs.
To Reproduce
- Call
pstget() to read a persisted message while the system is under memory pressure
- Ensure
fopen() succeeds (file exists and is readable)
- Ensure
malloc(fileLen) fails (e.g., by exhausting available memory)
- The function returns
PAHO_MEMORY_ERROR without closing fp
Expected behavior
The file handle should be closed on all error paths, including when the buffer allocation fails.
Screenshots
N/A
Log files
N/A
Environment:
- OS: Linux
- Version: develop branch, file
src/MQTTPersistenceDefault.c
Additional context
The leak occurs in this code path:
fp = fopen(filename, "rb");
if (fp != NULL)
{
// ...
if ((buf = (char *)malloc(fileLen)) == NULL)
{
rc = PAHO_MEMORY_ERROR;
goto exit; // fp not closed here
}
// ...
fclose(fp); // only the success path closes it
}
exit:
return rc;
A fix would be to add fclose(fp) before goto exit on the allocation failure path, or to move fclose(fp) into the exit label for unified cleanup.
Describe the bug
In
pstget(), whenfopen()succeeds butmalloc()for the read buffer subsequently fails, the file handle is not closed before returning. This leaks aFILE*and its underlying file descriptor each time it occurs.To Reproduce
pstget()to read a persisted message while the system is under memory pressurefopen()succeeds (file exists and is readable)malloc(fileLen)fails (e.g., by exhausting available memory)PAHO_MEMORY_ERRORwithout closingfpExpected behavior
The file handle should be closed on all error paths, including when the buffer allocation fails.
Screenshots
N/A
Log files
N/A
Environment:
src/MQTTPersistenceDefault.cAdditional context
The leak occurs in this code path:
A fix would be to add
fclose(fp)beforegoto exiton the allocation failure path, or to movefclose(fp)into theexitlabel for unified cleanup.