From 1d5e652d24571fd6f4ef00b8ab885524b062a0fa Mon Sep 17 00:00:00 2001 From: Mohan Yelugoti Date: Fri, 1 Nov 2024 23:31:01 -0400 Subject: [PATCH] lib:vector:vlib: Fix possible null pointer dereference In the function `Vect_cat_list_to_array`, as part of the execution, if list turns out to not contain any numbers, `cats` internal variable is not changed from NULL. Without checking if `cats` is NULL or not, qsort or first elemnt of it is accessed, which can lead to null pointer dereference. To fix that issue, only access cats if it's not NULL. This issue was found using cppcheck tool. Signed-off-by: Mohan Yelugoti --- lib/vector/Vlib/cats.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/lib/vector/Vlib/cats.c b/lib/vector/Vlib/cats.c index 51e9accd240..7174389ff55 100644 --- a/lib/vector/Vlib/cats.c +++ b/lib/vector/Vlib/cats.c @@ -493,7 +493,7 @@ int Vect_cat_list_to_array(const struct cat_list *list, int **vals, int *nvals) G_debug(1, "Vect_cat_list_to_array()"); - *nvals = n_cats = 0; + *nvals = n_cats = n_ucats = 0; cats = NULL; for (i = 0; i < list->n_ranges; i++) { n = list->max[i] - list->min[i] + 1; @@ -509,13 +509,16 @@ int Vect_cat_list_to_array(const struct cat_list *list, int **vals, int *nvals) n_cats += n; } - /* sort array */ - qsort(cats, n_cats, sizeof(int), cmp); + if (cats) { + /* sort array */ + qsort(cats, n_cats, sizeof(int), cmp); + + /* skip duplicated values */ + ucats = G_malloc(sizeof(int) * n_cats); + last_cat = ucats[0] = cats[0]; + n_ucats = 1; + } - /* skip duplicated values */ - ucats = G_malloc(sizeof(int) * n_cats); - last_cat = ucats[0] = cats[0]; - n_ucats = 1; for (i = 1; i < n_cats; i++) { if (last_cat == cats[i]) continue;