vector paranoia
authorHannes Reinecke <hare@suse.de>
Fri, 13 May 2011 10:21:16 +0000 (12:21 +0200)
committerHannes Reinecke <hare@suse.de>
Fri, 13 May 2011 10:21:16 +0000 (12:21 +0200)
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 <hare@suse.de>
libmultipath/vector.c

index ea6f82c..652f118 100644 (file)
@@ -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;
 }