Original link
Alternative ways of allocating memory in Mbed TLS — Mbed TLS documentation
In some cases, such as when there is no operating system on an embedded platform, the heap and calloc()
/ free()
or is not really available. Mbed TLS still requires some form of dynamic memory allocation to operate the SSL stack. We could assume a maximum size for all structures, but this would consume a lot of memory space. Instead, we chose to have Mbed TLS only use hooks to allocate and deallocate dynamic memory.
Currently you have two options:
-
Provide your own allocation and deallocation functions.
-
Use the buffer allocator function in Mbed TLS.
To enable the memory allocation layer, define MBEDTLS_PLATFORM_C
and MBEDTLS_PLATFORM_MEMORY
in mbedtls_config.h
. See How to configure Mbed TLS .
If the layer is not enabled, the libc standard sum calloc()
is free()
used.
Internal components
Internally, there are only two function pointers mbedtls_calloc()
and mbedtls_free()
calls for each dynamic memory allocation or deallocation in Mbed TLS.
extern void * (*mbedtls_calloc)( size_t n, size_t size ); extern void (*mbedtls_free)( void *ptr );
libc
The prototypes and standard calloc()
sums of these functions free()
. Without any further calls, libc
these pointers are given names by default.
no libc equivalent
If your system does not have libc
an equivalent, you will get compile errors like the following calloc()
or free()
not found.
Defines MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
in mbedtls_config.h
the file prevent Mbed TLS from understanding these functions.
Provide your own hooks
If your operating system already provides libc
allocator functions, you can set them with:
int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ), void (*free_func)( void * ) );
Use the Mbed TLS buffer allocator
If you want Mbed TLS to allocate all the content in the static buffer, you can define it MBEDTLS_MEMORY_BUFFER_ALLOC_C
in mbedtls_config.h
the file.
Before calling any other Mbed TLS functions, enable the buffer allocator as follows:
unsigned char memory_buf[100000]; mbedtls_memory_buffer_alloc_init( memory_buf, sizeof(memory_buf) );
Safety Warning
A buffer allocator is a simple approach to a dynamic memory allocator. No special heap protection mechanisms are implemented.
Use the buffer allocator elsewhere
The buffer allocator itself does not depend on any other part of Mbed TLS. So you can use it in your own code base as well.