Skip to content

File handle leak in pstget() when the read buffer allocation fails #1681

Description

@K-ANOY

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

  1. Call pstget() to read a persisted message while the system is under memory pressure
  2. Ensure fopen() succeeds (file exists and is readable)
  3. Ensure malloc(fileLen) fails (e.g., by exhausting available memory)
  4. 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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions