From ed06c6122dba3a42cd6be3ab43e37840644d559d Mon Sep 17 00:00:00 2001 From: Hannes Reinecke Date: Fri, 13 May 2011 12:21:16 +0200 Subject: [PATCH] vector paranoia As usual error checking in vector.c is non-existent. In this case, if realloc fails we will return NULL but leave ->allocated on the previous value. And checking for empty vectors isn't a bad idea, either. Signed-off-by: Hannes Reinecke --- libmultipath/vector.c | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/libmultipath/vector.c b/libmultipath/vector.c index ea6f82c..652f118 100644 --- a/libmultipath/vector.c +++ b/libmultipath/vector.c @@ -38,14 +38,21 @@ vector_alloc(void) void * vector_alloc_slot(vector v) { + void *new_slot = NULL; + + if (!v) + return NULL; + v->allocated += VECTOR_DEFAULT_SIZE; if (v->slot) - v->slot = REALLOC(v->slot, sizeof (void *) * v->allocated); + new_slot = REALLOC(v->slot, sizeof (void *) * v->allocated); else - v->slot = (void *) MALLOC(sizeof (void *) * v->allocated); + new_slot = (void *) MALLOC(sizeof (void *) * v->allocated); - if (!v->slot) + if (!new_slot) v->allocated -= VECTOR_DEFAULT_SIZE; + else + v->slot = new_slot; return v->slot; } @@ -99,7 +106,7 @@ vector_del_slot(vector v, int slot) { int i; - if (!v->allocated || slot < 0 || slot > VECTOR_SIZE(v)) + if (!v || !v->allocated || slot < 0 || slot > VECTOR_SIZE(v)) return; for (i = slot + 1; i < (v->allocated / VECTOR_DEFAULT_SIZE); i++) @@ -110,9 +117,16 @@ vector_del_slot(vector v, int slot) if (!v->allocated) { FREE(v->slot); v->slot = NULL; + v->allocated = 0; + } else { + void *new_slot; + + new_slot = REALLOC(v->slot, sizeof (void *) * v->allocated); + if (!new_slot) + v->allocated += VECTOR_DEFAULT_SIZE; + else + v->slot = new_slot; } - else - v->slot = REALLOC(v->slot, sizeof (void *) * v->allocated); } void @@ -120,7 +134,7 @@ vector_repack(vector v) { int i; - if (!v->allocated) + if (!v || !v->allocated) return; for (i = 0; i < (v->allocated / VECTOR_DEFAULT_SIZE); i++) @@ -138,6 +152,8 @@ vector_free(vector v) if (v->slot) FREE(v->slot); + v->allocated = 0; + v->slot = NULL; FREE(v); } @@ -161,7 +177,11 @@ free_strvec(vector strvec) void vector_set_slot(vector v, void *value) { - unsigned int i = v->allocated - 1; + unsigned int i; + + if (!v) + return; + i = VECTOR_SIZE(v) - 1; v->slot[i] = value; } -- 2.7.4