Skip to content

Commit

Permalink
Fix destructor dereferencing (#53)
Browse files Browse the repository at this point in the history
* fix segfault caused by passing destructed value to `cvector_free` with
  `cvector_destructor`
* add unit test for dereferencing vector in cvector_destructor
  • Loading branch information
dm9pZCAq authored Apr 29, 2023
1 parent 152a353 commit 61ccddf
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
6 changes: 3 additions & 3 deletions cvector.h
Original file line number Diff line number Diff line change
Expand Up @@ -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( \
Expand All @@ -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); \
Expand All @@ -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__); \
Expand Down
21 changes: 21 additions & 0 deletions unit-tests.c
Original file line number Diff line number Diff line change
Expand Up @@ -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();

0 comments on commit 61ccddf

Please sign in to comment.