lib/axmap: Make axmap_new() more robust
authorBart Van Assche <bart.vanassche@wdc.com>
Wed, 22 Aug 2018 16:00:15 +0000 (09:00 -0700)
committerBart Van Assche <bvanassche@acm.org>
Thu, 23 Aug 2018 01:59:24 +0000 (18:59 -0700)
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 <bart.vanassche@wdc.com>
lib/axmap.c

index 0d8fbf8dfaef93d99aac516dfe290074c5d27349..781a10395ac5b79a142078960260ba497336fa2f 100644 (file)
@@ -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;
 }