diff mbox series

Inspect command leaks memory if realloc() fails

Message ID CALjJ9cdoxY7E4omFtXcZigNV9Q8_+q95do=b=PrzsN+JbBK23Q@mail.gmail.com (mailing list archive)
State New
Headers show
Series Inspect command leaks memory if realloc() fails | expand

Commit Message

Nathan Mills April 5, 2024, 3:55 p.m. UTC
In `cmd_inspect_list_chunks()` in Btrfs v6.8-g3793e987 on the master
branch, there is this code on line 1167:
```c
ctx.stats = realloc(ctx.stats, ctx.size * sizeof(ctx.stats[0]));
```

This is a "common realloc mistake" according to CppCheck. The fix is
to assign the result of realloc to a temporary variable and only
assign the original variable if the temp is non-NULL. That way we
don't lose the pointer to the old memory.

I found this by grepping the source for this regex:
`([A-Za-z_0-9->\.]+)\s*=\s*realloc\s*\(\s*\1` after noticing a
CppCheck warning for a different part of btrfs that already uses a
temporary to hold the reallocated memory.

Here's a patch to fix it (note: this patch probably won't apply to
devel because the goto label has been changed in `v6.8-19-g512fa7e6`):

commit 7f65051ee07a46a9cb7e0aa0134af0cc77db0a16 (HEAD ->
realloc-memory-leak, myfork/realloc-memory-leak)
Author: Nathan Mills <38995150+Quipyowert2@users.noreply.github.com>
Date:   Thu Apr 4 19:34:28 2024 -0700

    btrfs-progs: cmds: fix inspect memory leak.

                                }
                        }
diff mbox series

Patch

diff --git a/cmds/inspect.c b/cmds/inspect.c
index 145196d0..e665a281 100644
--- a/cmds/inspect.c
+++ b/cmds/inspect.c
@@ -1162,12 +1162,15 @@  static int cmd_inspect_list_chunks(const
struct cmd_struct *cmd,

                                if (ctx.length == ctx.size) {
                                        ctx.size += 1024;
-                                       ctx.stats = realloc(ctx.stats, ctx.size
+                                       struct list_chunks_entry *tmp;
+                                       tmp = realloc(ctx.stats, ctx.size
                                                * sizeof(ctx.stats[0]));
-                                       if (!ctx.stats) {
+                                       if (!tmp) {
                                                ret = 1;

error_msg(ERROR_MSG_MEMORY, NULL);
                                                goto out_nomem;
+                                       } else {
+                                               ctx.stats = tmp;
                                        }