diff options
author | Tucker Evans <tucker@tuckerevans.com> | 2020-07-02 19:20:05 -0400 |
---|---|---|
committer | Tucker Evans <tucker@tuckerevans.com> | 2020-07-04 22:28:36 -0400 |
commit | e4ea23a6c23acdec86e5b5fcd34c653118f6898e (patch) | |
tree | d91e3b1dd813e1ab084369162e6c444b1c70a0f6 | |
parent | 98454f841b5ac87d2253c2fae0aba2525853f907 (diff) |
Adds free & clear functions to vectors
-rw-r--r-- | collections/vector/vector.adoc | 48 | ||||
-rw-r--r-- | collections/vector/vector.c | 22 | ||||
-rw-r--r-- | collections/vector/vector.h | 2 |
3 files changed, 71 insertions, 1 deletions
diff --git a/collections/vector/vector.adoc b/collections/vector/vector.adoc index 8ec8b49..3ffd10c 100644 --- a/collections/vector/vector.adoc +++ b/collections/vector/vector.adoc @@ -1,7 +1,7 @@ Vector ====== Tucker Evans -v0.4, 2020-07-02 +v0.5, 2020-07-02 A basic vector, that hold pointers to your data structures. @@ -123,3 +123,49 @@ vec_push(vector, str_dup(str2)); assert(str_cmp(vec_pop(vector), str2) == 0); assert(str_cmp(vec_pop(vector), str1) == 0); ---- + +[[vec_free]] ++void vec_free(vec *self)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~ +Frees all internal memory and +self+. + +NOTE: All item pointers are still valid after a call to +<<vec_free,+vec_free()+>>, <<vec_clear,+vec_clear()+>> should be called before +if they are no longer needed to avoid memory leaks. + +Examples +^^^^^^^^ +[source,c] +---- +#include "vector.h" + +vec *vector = vec_new(); +vec_free(vector); +---- + +[[vec_clear]] ++void vec_clear(vec *self)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Free all elements within vector +self+, and sets vector to empty (size 0). + +NOTE: Does not free internal memory of +self+ or +self+ itself, if this is desired +<<vec_free,+vec_free()+>> should be called immediatly after this. + +Examples +^^^^^^^^ +[source,c] +---- +#include "vector.h" +#include <string.h> + +char *str1 = "ONE"; +char *str2 = "TWO"; + +vec *vector = vec_new(); +vec_push_back(vector, str_dup(str1)); +vec_push_back(vector, str_dup(str2)); + +vec_clear(vector); +assert(vec_size(vector) == 0); +vec_free(vector); +---- diff --git a/collections/vector/vector.c b/collections/vector/vector.c index 936c0c8..9544917 100644 --- a/collections/vector/vector.c +++ b/collections/vector/vector.c @@ -96,3 +96,25 @@ vec *root; return root->base[--root->end]; } + +void vec_free(root) +vec *root; +{ + free(root->base); + root->base = NULL; + + free(root); +} + +void vec_clear(root) +vec *root; +{ + int i; + + for (i = 0; i < root->end; i++) { + free(vec_index(root, i)); + } + + root->end = 0; +} + diff --git a/collections/vector/vector.h b/collections/vector/vector.h index 81eea22..3996030 100644 --- a/collections/vector/vector.h +++ b/collections/vector/vector.h @@ -9,4 +9,6 @@ int vec_size(vec*); void vec_push(vec*, void*); void* vec_index(vec*, int); void* vec_pop(vec*); +void vec_free(vec*); +void vec_clear(vec*); #endif |