From 00e2cc3d88b07734c4e04bb783e83fbbde557e53 Mon Sep 17 00:00:00 2001 From: Prathamesh Deshpande Date: Sat, 13 Jul 2024 03:03:25 +0530 Subject: [PATCH] needed to pass vector pointer-to-pointer to ensure no use after frees --- README.md | 4 +++- include/data_structures/vector/vector.h | 15 ++++++++------- .../vector/vector_primitive_test.c | 6 +++--- 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 459b611..1162bb7 100644 --- a/README.md +++ b/README.md @@ -15,10 +15,12 @@ Initially, I was going to write it in the OOP C Pattern (pointers to functions i ### To Do - [x] Look into GitHub actions based testing +- [x] Valgrind testing? - [x] How can I integrate CMake, CTest, GitHub actions and Valgrind? - [ ] Write primitive as well as pointer-to-structs examples - [ ] Examples should try to break the framework as much as possible -- [x] Valgrind testing? +- [ ] Use constant pointers, pointers to constants and constant pointers to constant wherever applicable. + ### Checklist - Each function, with pointer params, should check for NULL for each pointer, diff --git a/include/data_structures/vector/vector.h b/include/data_structures/vector/vector.h index 1e11c99..ea0b7d5 100644 --- a/include/data_structures/vector/vector.h +++ b/include/data_structures/vector/vector.h @@ -173,19 +173,20 @@ bool linear_search_##NAME(NAME* obj, TYPE ref ,bool (*comparator)(TYPE, TYPE), u }\ return false;\ }\ -bool delete_##NAME(NAME* obj, bool (*delete_type)(TYPE)){\ - if(!obj){\ +bool delete_##NAME(NAME** obj, bool (*delete_type)(TYPE)){\ + if(!obj || !*obj){\ return false;\ }\ - if(obj->data){\ + if((*obj)->data){\ if(delete_type){\ - for(uint64_t i = 0; isize; ++i){\ - delete_type(obj->data[i]);\ + for(uint64_t i = 0; i<(*obj)->size; ++i){\ + delete_type((*obj)->data[i]);\ }\ }\ - free(obj->data);\ + free((*obj)->data);\ }\ - free(obj);\ + free(*(obj));\ + *obj = NULL;\ return true;\ }\ bool clear_##NAME(NAME* obj, bool (*delete_type)(TYPE), TYPE val){\ diff --git a/tests/data_structures/vector/vector_primitive_test.c b/tests/data_structures/vector/vector_primitive_test.c index 09f309c..fbcba05 100644 --- a/tests/data_structures/vector/vector_primitive_test.c +++ b/tests/data_structures/vector/vector_primitive_test.c @@ -43,7 +43,7 @@ int main(void){ puts("Empty vector not nulled"); return -1; } - delete_intVec(iv,NULL); + delete_intVec(&iv,NULL); if(iv!=NULL){ puts("Deleted integer vector still points to memory"); return -1; @@ -60,7 +60,7 @@ int main(void){ puts("Vector data is NULL even though size is not 0"); return -1; } - delete_intVec(iv, NULL); + delete_intVec(&iv, NULL); if(iv!=NULL){ puts("Deleted vector of +ve size is not NULL"); return -1; @@ -76,7 +76,7 @@ int main(void){ puts("Vector data is NULL at size UINT64_MAX"); return -1; } - delete_intVec(iv,NULL); + delete_intVec(&iv,NULL); if(iv!=NULL){ puts("Vector is not null after being freed at UINT64_MAX"); return -1;