Skip to content

Conversation

@huffman-coder
Copy link

This PR is intended to address #75

This change allows consumers to replace standard library memory management functions (malloc and free) with their own memory allocator functions without changing the tinycbor code. Since this seems most useful in an embedded context, this change is scoped to the cborparser_dup_string.c parser file only.

One goal of this update is to be fully backward compatible with existing code. Current consumers of this library who want to continue to use the standard library memory management functions do not need to make any changes to their code or project configuration.

Consumers who want to replace malloc and free should create a header file that defines cbor_malloc and cbor_free. Then, they set this header file as the value of the CBOR_CUSTOM_ALLOC_INCLUDE macro. For example, if the header file is named cbor_alloc.h, they would add this to the project settings:

-DCBOR_CUSTOM_ALLOC_INCLUDE=\"cbor_alloc.h\"

(This implementation pattern is used in other projects such as mbedtls to facilitate customization where the default implementation does not meet the project's needs.)

For cases where the replacement functions have the same function signature as malloc and free, macro replacement can be used to define cbor_malloc and cbor_free. This allows replacement with no additional cost to the call stack. For example, consumers who wish to replace malloc and free with FreeRTOS heap functions can create the following simple header:

#include "FreeRTOS.h"

#define cbor_malloc pvPortMalloc
#define cbor_free vPortFree

For cases where the replacement functions have different function signatures than malloc and free, cbor_malloc and cbor_free can be defined as functions that wrap the replacement functions. Function prototypes in the header would look like this:

#include <stddef.h>

void* cbor_malloc(size_t size);
void cbor_free(void* ptr);

Copy link
Member

@thiagomacieira thiagomacieira left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, thanks!

@thiagomacieira thiagomacieira merged commit 75eaa19 into intel:main Sep 10, 2022
@huffman-coder huffman-coder deleted the custom-allocator branch September 13, 2022 12:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants