From 61ccddf8c73101db701aefb2d788d8d77064e57c Mon Sep 17 00:00:00 2001 From: dm9pZCAq <46228973+dm9pZCAq@users.noreply.github.com> Date: Sat, 29 Apr 2023 19:47:38 +0300 Subject: [PATCH] Fix destructor dereferencing (#53) * fix segfault caused by passing destructed value to `cvector_free` with `cvector_destructor` * add unit test for dereferencing vector in cvector_destructor --- cvector.h | 6 +++--- unit-tests.c | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/cvector.h b/cvector.h index 3c7eea3..bcb55e4 100644 --- a/cvector.h +++ b/cvector.h @@ -136,7 +136,7 @@ typedef struct cvector_metadata_t { if ((i) < cv_sz__) { \ cvector_elem_destructor_t elem_destructor__ = cvector_elem_destructor(vec); \ if (elem_destructor__) { \ - elem_destructor__(&vec[i]); \ + elem_destructor__(&(vec)[i]); \ } \ cvector_set_size((vec), cv_sz__ - 1); \ memmove( \ @@ -159,7 +159,7 @@ typedef struct cvector_metadata_t { if (elem_destructor__) { \ size_t i__; \ for (i__ = 0; i__ < cvector_size(vec); ++i__) { \ - elem_destructor__(&vec[i__]); \ + elem_destructor__(&(vec)[i__]); \ } \ } \ cvector_set_size(vec, 0); \ @@ -179,7 +179,7 @@ typedef struct cvector_metadata_t { if (elem_destructor__) { \ size_t i__; \ for (i__ = 0; i__ < cvector_size(vec); ++i__) { \ - elem_destructor__(&vec[i__]); \ + elem_destructor__(&(vec)[i__]); \ } \ } \ cvector_clib_free(p1__); \ diff --git a/unit-tests.c b/unit-tests.c index bb20982..a5419bd 100644 --- a/unit-tests.c +++ b/unit-tests.c @@ -237,4 +237,25 @@ UTEST(test, test_complex_insert) { cvector_free(vec); } +void cvector_free_destructor(void *p) { + free(*(void **)p); +} + +UTEST(test, derefence_destructor) { + cvector_vector_type(char *) v = NULL; + cvector_init(v, 2, cvector_free_destructor); + + char *ptr; + ptr = strdup("hello"); + ASSERT_TRUE(!!ptr); + cvector_push_back(v, ptr); + + ptr = strdup("world"); + ASSERT_TRUE(!!ptr); + cvector_push_back(v, ptr); + + cvector_vector_type(char *) *vec_ptr = &v; + cvector_free(*vec_ptr); +} + UTEST_MAIN();