Skip to content
This repository was archived by the owner on May 27, 2021. It is now read-only.

Custom Memory Allocator Macros #16

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
8 changes: 4 additions & 4 deletions src/vec.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;
Expand Down
13 changes: 12 additions & 1 deletion src/vec.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@


#define vec_deinit(v)\
( free((v)->data),\
( VEC_FREE((v)->data),\
vec_init(v) )


Expand Down Expand Up @@ -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,
Expand Down