Browse Source

faux.vec: Fix deletion of last item from vector. +Regression test

Serj Kalichev 2 years ago
parent
commit
4723f4d471
2 changed files with 15 additions and 0 deletions
  1. 6 0
      faux/vec/testc_vec.c
  2. 9 0
      faux/vec/vec.c

+ 6 - 0
faux/vec/testc_vec.c

@@ -88,6 +88,12 @@ int testc_faux_vec(void)
 		goto err;
 	}
 
+	// Remove all items one by one. Note current len is (VEC_LEN - 1).
+	// Checks for case when length of vector is 1 and we delete this
+	// left item.
+	for (i = 0; i < (VEC_LEN - 1); i++)
+		faux_vec_del(vec, 0);
+
 	ret = 0;
 err:
 	faux_vec_free(vec);

+ 9 - 0
faux/vec/vec.c

@@ -174,6 +174,15 @@ ssize_t faux_vec_del(faux_vec_t *faux_vec, unsigned int index)
 	if ((index + 1) > faux_vec_len(faux_vec))
 		return -1;
 
+	// It's special case when the only one item left within vector. In this
+	// case we don't need to realloc() but free() the vector.
+	if (faux_vec_len(faux_vec) == 1) {
+		free(faux_vec->data);
+		faux_vec->data = NULL;
+		faux_vec->len = 0;
+		return 0;
+	}
+
 	// Move following items to fill the space of deleted item
 	if (index != (faux_vec_len(faux_vec) - 1)) { // Is it last item?
 		void *item_to_del = faux_vec_item(faux_vec, index);