diff --git a/include/rcutils/allocator.h b/include/rcutils/allocator.h index b6c76ba6..9e7c5c7c 100644 --- a/include/rcutils/allocator.h +++ b/include/rcutils/allocator.h @@ -108,6 +108,21 @@ RCUTILS_WARN_UNUSED rcutils_allocator_t rcutils_get_default_allocator(void); +/// Override the default allocator returned by rcutils_get_default_allocator. +/** + * Attribute | Adherence + * ------------------ | ------------- + * Allocates Memory | No + * Thread-Safe | No + * Uses Atomics | No + * Lock-Free | Yes + * + * \param[in] override_allocator The allocator to set as the default. + */ +RCUTILS_PUBLIC +void +rcutils_set_default_allocator(rcutils_allocator_t override_allocator); + /// Return true if the given allocator has non-null function pointers. /** * \param[in] allocator to be checked by the function diff --git a/src/allocator.c b/src/allocator.c index d364bded..45494285 100644 --- a/src/allocator.c +++ b/src/allocator.c @@ -69,9 +69,23 @@ rcutils_get_zero_initialized_allocator(void) return zero_allocator; } +static rcutils_allocator_t rcutils_override_default_allocator = {0}; + +void +rcutils_set_default_allocator(rcutils_allocator_t override_allocator) +{ + if (rcutils_allocator_is_valid(&override_allocator)) { + rcutils_override_default_allocator = override_allocator; + } +} + rcutils_allocator_t rcutils_get_default_allocator(void) { + if (rcutils_allocator_is_valid(&rcutils_override_default_allocator)) { + return rcutils_override_default_allocator; + } + static rcutils_allocator_t default_allocator = { .allocate = __default_allocate, .deallocate = __default_deallocate, @@ -79,6 +93,7 @@ rcutils_get_default_allocator(void) .zero_allocate = __default_zero_allocate, .state = NULL, }; + return default_allocator; }