[PATCH] tools: lib: subcmd: Fix null pointer dereference

From: Tapasweni Pathak
Date: Sat Sep 29 2018 - 13:03:35 EST


Add null check before dereferencing ent. ent is pointer to memory
allocated using malloc and is dereferenced immediately without
null check.

Found using Facebook's Infer. Build tested it.

Signed-off-by: Tapasweni Pathak <tapaswenipathak@xxxxxxxxx>
---
Another option is to dereference only inside if (ent).
tools/lib/subcmd/help.c | 7 ++++++-
1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/tools/lib/subcmd/help.c b/tools/lib/subcmd/help.c
index 2859f10..b805d1d 100644
--- a/tools/lib/subcmd/help.c
+++ b/tools/lib/subcmd/help.c
@@ -16,13 +16,18 @@
void add_cmdname(struct cmdnames *cmds, const char *name, size_t len)
{
struct cmdname *ent = malloc(sizeof(*ent) + len + 1);
-
+ if (!ent) {
+ printf("mem alloc failed\n");
+ goto error;
+ }
ent->len = len;
memcpy(ent->name, name, len);
ent->name[len] = 0;

ALLOC_GROW(cmds->names, cmds->cnt + 1, cmds->alloc);
cmds->names[cmds->cnt++] = ent;
+ error:
+ if (ent) free(ent);
}

void clean_cmdnames(struct cmdnames *cmds)
--
2.7.4