From 70c0f35624b32a86603c034e28e6b09907868100 Mon Sep 17 00:00:00 2001 From: Bart Van Assche Date: Wed, 22 Aug 2018 09:00:15 -0700 Subject: [PATCH] lib/axmap: Make axmap_new() more robust Return NULL instead of triggering a segmentation fault if calloc() fails. Note: calling free(NULL) is safe so it is not necessary to check the free() argument before calling free(). Signed-off-by: Bart Van Assche --- lib/axmap.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/lib/axmap.c b/lib/axmap.c index 0d8fbf8d..781a1039 100644 --- a/lib/axmap.c +++ b/lib/axmap.c @@ -128,6 +128,8 @@ struct axmap *axmap_new(unsigned long nr_bits) axmap->nr_levels = levels; axmap->levels = calloc(axmap->nr_levels, sizeof(struct axmap_level)); + if (!axmap->levels) + goto free_axmap; axmap->nr_bits = nr_bits; for (i = 0; i < axmap->nr_levels; i++) { @@ -137,19 +139,21 @@ struct axmap *axmap_new(unsigned long nr_bits) al->map_size = (nr_bits + BLOCKS_PER_UNIT - 1) >> UNIT_SHIFT; al->map = malloc(al->map_size * sizeof(unsigned long)); if (!al->map) - goto err; + goto free_levels; nr_bits = (nr_bits + BLOCKS_PER_UNIT - 1) >> UNIT_SHIFT; } axmap_reset(axmap); return axmap; -err: + +free_levels: for (i = 0; i < axmap->nr_levels; i++) - if (axmap->levels[i].map) - free(axmap->levels[i].map); + free(axmap->levels[i].map); free(axmap->levels); + +free_axmap: free(axmap); return NULL; } -- 2.25.1