From 6dc445c1bbccbb86df9874f7c86f618f2e6366fb Mon Sep 17 00:00:00 2001 From: daiyanlong Date: Sat, 26 Apr 2025 16:29:59 +0800 Subject: [PATCH] ibdiag_sa: Fix memory leak in sa_query() When realloc() fails on line 142 of infiniband-diags/ibdiag_sta. c, it will cause the loss of the umad's original memory reference, resulting in a leak of the original memory. The modified logic is to store the result in a temporary variable new_umad before calling realloc, which can avoid directly overwriting the original pointer umad and prevent losing the reference to the original memory when realloc fails. Signed-off-by: daiyanlong --- infiniband-diags/ibdiag_sa.c | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/infiniband-diags/ibdiag_sa.c b/infiniband-diags/ibdiag_sa.c index 2ea0801e4..5c4db68da 100644 --- a/infiniband-diags/ibdiag_sa.c +++ b/infiniband-diags/ibdiag_sa.c @@ -104,7 +104,7 @@ int sa_query(struct sa_handle * h, uint8_t method, struct sa_query_result *result) { ib_rpc_t rpc; - void *umad, *mad; + void *umad, *mad, *new_umad; int ret, offset, len = 256; memset(&rpc, 0, sizeof(rpc)); @@ -139,7 +139,13 @@ int sa_query(struct sa_handle * h, uint8_t method, ret = umad_recv(h->fd, umad, &len, ibd_timeout); if (ret < 0) { if (errno == ENOSPC) { - umad = realloc(umad, umad_size() + len); + new_umad = realloc(umad, umad_size() + len); + if (!new_umad) { + IBWARN("Failed to reallocate memory for umad: %s\n", strerror(errno)); + free(umad); + return (-ret); + } + umad = new_umad; goto recv_mad; } IBWARN("umad_recv failed: attr 0x%x: %s\n", attr,