From 5a6e2fd02ae5aaea753788b797d553f62cc0244b Mon Sep 17 00:00:00 2001 From: Jakub Jelen Date: Mon, 11 Aug 2025 20:19:44 +0200 Subject: [PATCH] poll: Fix memory leak on failed realloc() In cases where this is the initial allocation, the shrinking of the polltrs buffer would result in 0B realloc, which really does not make sense. Also, when this second realloc fails, the memory is never freed as the outer code believes there is nothing allocated on the poll_ctx Signed-off-by: Jakub Jelen Reviewed-by: Andreas Schneider --- src/poll.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/poll.c b/src/poll.c index 09f6ec08..215add7a 100644 --- a/src/poll.c +++ b/src/poll.c @@ -572,25 +572,33 @@ static int ssh_poll_ctx_resize(ssh_poll_ctx ctx, size_t new_size) pollptrs = realloc(ctx->pollptrs, sizeof(ssh_poll_handle) * new_size); if (pollptrs == NULL) { - return -1; + /* Fail, but keep the old value to be freed later */ + return SSH_ERROR; } ctx->pollptrs = pollptrs; pollfds = realloc(ctx->pollfds, sizeof(ssh_pollfd_t) * new_size); if (pollfds == NULL) { + if (ctx->polls_allocated == 0) { + /* This was initial allocation -- just free what we allocated above + * and fail */ + SAFE_FREE(ctx->pollptrs); + return SSH_ERROR; + } + /* Try to realloc the pollptrs back to the original size */ pollptrs = realloc(ctx->pollptrs, sizeof(ssh_poll_handle) * ctx->polls_allocated); if (pollptrs == NULL) { - return -1; + return SSH_ERROR; } ctx->pollptrs = pollptrs; - return -1; + return SSH_ERROR; } ctx->pollfds = pollfds; ctx->polls_allocated = new_size; - return 0; + return SSH_OK; } /**