From: Wolfgang Stöggl Date: Thu, 11 Jul 2019 13:00:09 +0000 (+0200) Subject: Use temp pointer for realloc() X-Git-Tag: v1.8.0~75 X-Git-Url: http://git.ipfire.org/gitweb/gitweb.cgi?a=commitdiff_plain;h=59b1bcbaeab056e774a4ba244e70f8401eecb1ae;p=thirdparty%2Frrdtool-1.x.git Use temp pointer for realloc() If realloc() fails, it returns NULL and the original block is left untouched; it is not freed. Use a temporary pointer first to check, if realloc() has failed. - Fixes the following Cppcheck errors: [src/rrd_create.c:958] (error) Common realloc mistake: 'mappings' nulled but not freed upon failure [memleakOnRealloc] [src/rrd_create.c:2451] (error) Common realloc mistake: 'candidates' nulled but not freed upon failure [memleakOnRealloc] [src/rrd_daemon.c:2402] (error) Common realloc mistake: 'sources' nulled but not freed upon failure [memleakOnRealloc] --- diff --git a/src/rrd_create.c b/src/rrd_create.c index 6533eb5a..0cb5b78c 100644 --- a/src/rrd_create.c +++ b/src/rrd_create.c @@ -955,12 +955,13 @@ int rrd_create_r2( parseDS(argv[i] + 3, rrd.ds_def + rrd.stat_head->ds_cnt, &rrd, lookup_DS, &m, &require_version); - mappings = + mapping_t *mappings_tmp = realloc(mappings, sizeof(mapping_t) * (mappings_cnt + 1)); - if (!mappings) { + if (!mappings_tmp) { rrd_set_error("allocating mappings"); goto done; } + mappings = mappings_tmp; memcpy(mappings + mappings_cnt, &m, sizeof(mapping_t)); mappings_cnt++; @@ -2448,14 +2449,16 @@ static candidate_t *find_matching_candidates( (void *) target); } - candidates = realloc(candidates, - sizeof(candidate_t) * (cnt + - candidate_cnt_for_source)); - if (candidates == NULL) { + candidate_t *candidates_tmp = realloc(candidates, + sizeof(candidate_t) * + (cnt + + candidate_cnt_for_source)); + if (candidates_tmp == NULL) { rrd_set_error("Cannot realloc memory"); free(candidates_for_source); goto done; } + candidates = candidates_tmp; memcpy(candidates + cnt, candidates_for_source, sizeof(candidate_t) * candidate_cnt_for_source); diff --git a/src/rrd_daemon.c b/src/rrd_daemon.c index 10385799..806f6355 100644 --- a/src/rrd_daemon.c +++ b/src/rrd_daemon.c @@ -2399,13 +2399,15 @@ static int handle_request_create( rc = syntax_error(sock, cmd); goto done; } - sources = realloc(sources, sizeof(char *) * (sources_length + 2)); - if (sources == NULL) { + char **sources_tmp = + realloc(sources, sizeof(char *) * (sources_length + 2)); + if (sources_tmp == NULL) { rc = send_response(sock, RESP_ERR, "Cannot allocate memory\n"); goto done; } + sources = sources_tmp; flush_file(tok); sources[sources_length++] = tok;