diff --git a/README.md b/README.md index 8ba3e8b..7156c7b 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,9 @@ on it. This will free any memory the vector allocated during use. vec_deinit(&v); ``` +To use your own custom memory allocator, define both `VEC_FREE` and `VEC_REALLOC` +before including `vec.h`, and they will be used instead of the standard library's +`free` and `realloc`. ## Types vec.h provides the following predefined vector types: diff --git a/src/vec.c b/src/vec.c index 399104e..4ef9b9d 100644 --- a/src/vec.c +++ b/src/vec.c @@ -12,7 +12,7 @@ int vec_expand_(char **data, int *length, int *capacity, int memsz) { if (*length + 1 > *capacity) { void *ptr; int n = (*capacity == 0) ? 1 : *capacity << 1; - ptr = realloc(*data, n * memsz); + ptr = VEC_REALLOC(*data, n * memsz); if (ptr == NULL) return -1; *data = ptr; *capacity = n; @@ -24,7 +24,7 @@ int vec_expand_(char **data, int *length, int *capacity, int memsz) { int vec_reserve_(char **data, int *length, int *capacity, int memsz, int n) { (void) length; if (n > *capacity) { - void *ptr = realloc(*data, n * memsz); + void *ptr = VEC_REALLOC(*data, n * memsz); if (ptr == NULL) return -1; *data = ptr; *capacity = n; @@ -45,14 +45,14 @@ int vec_reserve_po2_( int vec_compact_(char **data, int *length, int *capacity, int memsz) { if (*length == 0) { - free(*data); + VEC_FREE(*data); *data = NULL; *capacity = 0; return 0; } else { void *ptr; int n = *length; - ptr = realloc(*data, n * memsz); + ptr = VEC_REALLOC(*data, n * memsz); if (ptr == NULL) return -1; *capacity = n; *data = ptr; diff --git a/src/vec.h b/src/vec.h index 2430611..d07fb05 100644 --- a/src/vec.h +++ b/src/vec.h @@ -27,7 +27,7 @@ #define vec_deinit(v)\ - ( free((v)->data),\ + ( VEC_FREE((v)->data),\ vec_init(v) ) @@ -156,6 +156,17 @@ +#if defined(VEC_FREE) && defined(VEC_REALLOC) +// Both defined, no error +#elif !defined(VEC_REALLOC) && !defined(VEC_FREE) +// Neither defined, use stdlib +#define VEC_FREE free +#define VEC_REALLOC realloc +#else +#error "Must define all or none of VEC_FREE and VEC_REALLOC." +#endif + + int vec_expand_(char **data, int *length, int *capacity, int memsz); int vec_reserve_(char **data, int *length, int *capacity, int memsz, int n); int vec_reserve_po2_(char **data, int *length, int *capacity, int memsz,