This is an automated email from the ASF dual-hosted git repository.

acassis pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx-apps.git

commit ac3f8b72315895d2b4c07362a7e924170e78831b
Author: yukangzhi <[email protected]>
AuthorDate: Mon Oct 26 17:03:24 2026 +0800

    nshlib/top: fix memory leak on realloc failure.
    
    top_callback() used the 'p = realloc(p, ...)' anti-pattern: when
    realloc() fails it returns NULL and the original pointer is lost, so
    the original status array and all its attached td_buf buffers leak and
    the cleanup loop in cmd_top() can no longer free them.
    
    Use a temporary variable to hold the realloc() result and only assign
    it back to topstatus->status on success, keeping the original pointer
    valid for cleanup on failure.
    
    Assisted-by: Kiro
    Signed-off-by: yukangzhi <[email protected]>
---
 nshlib/nsh_proccmds.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/nshlib/nsh_proccmds.c b/nshlib/nsh_proccmds.c
index 0992f6e38..b204600af 100644
--- a/nshlib/nsh_proccmds.c
+++ b/nshlib/nsh_proccmds.c
@@ -792,15 +792,21 @@ static int top_callback(FAR struct nsh_vtbl_s *vtbl, FAR 
const char *dirpath,
     }
   else if (topstatus->index >= topstatus->size)
     {
-      topstatus->status =
+      FAR struct nsh_taskstatus_s **newstatus =
         realloc(topstatus->status,
                 sizeof(topstatus->status[0]) * topstatus->size * 2);
-      if (topstatus->status == NULL)
+
+      if (newstatus == NULL)
         {
+          /* Keep the original topstatus->status valid on failure so the
+           * cleanup path in cmd_top() can still free it.
+           */
+
           nsh_error(vtbl, g_fmtcmdfailed, "top", "realloc", NSH_ERRNO);
           return -ENOMEM;
         }
 
+      topstatus->status = newstatus;
       memset(&topstatus->status[topstatus->index], 0,
              sizeof(topstatus->status[0]) * topstatus->size);
       topstatus->size *= 2;

Reply via email to