From d5b2106644fbfc33822bc965195046c19fd11c3e Mon Sep 17 00:00:00 2001 From: Yegor Yefremov Date: Thu, 6 Jan 2022 11:28:39 +0100 Subject: [PATCH] term: fix memleakOnRealloc Assign the newly allocated value to a temporary variable and in the case where we cannot allocate memory, free the initial pointer. --- src/term.c | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/term.c b/src/term.c index 28aa6253..11acb59d 100644 --- a/src/term.c +++ b/src/term.c @@ -827,12 +827,26 @@ static int tokenize(char * s, char *** argv) nbuf[0] = 0; n++; if ((n % 20) == 0) { + char *buf_tmp; + char **bufv_tmp; /* realloc space for another 20 args */ bufsize += 20; nargs += 20; bufp = buf; - buf = realloc(buf, bufsize); - bufv = realloc(bufv, nargs*sizeof(char *)); + buf_tmp = realloc(buf, bufsize); + if (buf_tmp == NULL) { + free(buf); + free(bufv); + return -1; + } + buf = buf_tmp; + bufv_tmp = realloc(bufv, nargs*sizeof(char *)); + if (bufv_tmp == NULL) { + free(buf); + free(bufv); + return -1; + } + bufv = bufv_tmp; nbuf = &buf[l]; /* correct bufv pointers */ k = buf - bufp; @@ -950,6 +964,10 @@ int terminal_mode(PROGRAMMER * pgm, struct avrpart * p) /* tokenize command line */ argc = tokenize(q, &argv); + if (argc < 0) { + free(cmdbuf); + return argc; + } fprintf(stdout, ">>> "); for (i=0; i