add_new_comm(): Fix memory leak
PATCH 1/1 add_new_comm(): Fix memory leak
The pointer cmdlines need to be explicity freed in case the realloc() fails. Fix it by adding a free() if realloc() returns a NULL pointer.
--- tools/lib/traceevent/event-parse.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)
tools/lib/traceevent/event-parse.c +4 -3
@@ -284,12 +284,13 @@ static int add_new_comm(struct tep_handle *tep,return 0 ; } - cmdlines =realloc (cmdlines,sizeof (*cmdlines) * (tep->cmdline_count +1 )); -if (!cmdlines) { +struct tep_cmdline *new_cmdlines =realloc (cmdlines,sizeof (*cmdlines) * (tep->cmdline_count +1 )); +if (!new_cmdlines) { +free (cmdlines); errno =ENOMEM ;return -1 ; } - tep->cmdlines = cmdlines; + tep->cmdlines = new_cmdlines; key.comm =strdup (comm);if (!key.comm) {
Signature · 1 line
2.17.1
Quoted 14 lines · On Sun, 14 Jun 2020 14:14:53 -0400 Gaurav Singh <[email protected]> wrote:
The pointer cmdlines need to be explicity freed in case the
realloc()fails. Fix it by adding afree()ifrealloc()returns a NULL pointer.Signed-off-by Gaurav Singh <[email protected]>--- tools/lib/traceevent/event-parse.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-)tools/lib/traceevent/event-parse.c +0
-0
tools/lib/traceevent/event-parse.c static int add_new_comm(struct tep_handle *tep, · line 290
Quoted 9 lines
tools/lib/traceevent/event-parse.c +3
-2@@ -284,12 +284,13 @@ static int add_new_comm(struct tep_handle *tep,return 0 ; } - cmdlines =realloc (cmdlines,sizeof (*cmdlines) * (tep->cmdline_count +1 )); -if (!cmdlines) { +struct tep_cmdline *new_cmdlines =realloc (cmdlines,sizeof (*cmdlines) * (tep->cmdline_count +1 )); +if (!new_cmdlines) { +free (cmdlines); errno =ENOMEM ;
NAK! This was fine as is.
What you just did was make tep->cmdline point to freed data, which will crash later on when tep is freed, and we free tep->cmdline.
If we fail to realloc, then the caller of add_new_comm will get the report that it failed, and then can determine what to do next. We don't want to touch tep->cmdline on failure.
-- Steve
Quoted 7 lines
tools/lib/traceevent/event-parse.c +1
-1return -1 ; } - tep->cmdlines = cmdlines; + tep->cmdlines = new_cmdlines; key.comm =strdup (comm);if (!key.comm) {