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.
This commit is contained in:
Yegor Yefremov 2022-01-06 11:28:39 +01:00
parent 7bf9711392
commit d5b2106644
1 changed files with 20 additions and 2 deletions

View File

@ -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<argc; i++)