Mbed TLS is now part of TrustedFirmware.org.

Using mbedtls_free() with NULL pointer

Dec 17, 2017 19:31
Mark Butcher

Hi All

This is not an actual problem but a question about best practice in the code.

Is it good or bad style/practice to call mbedtls_free() with a NULL pointer?

I see that when this takes place the free() implementation will just ignore it but on the other hand I think that I have seen code which actually allocates dummy memory so that it can then clean it up with a free (possibly to avoid passing a NULL pointer)?

I see that often this code location frees a NULL pointer.

void mbedtls_pem_free( mbedtls_pem_context *ctx )
    mbedtls_free( ctx->buf );
    mbedtls_free( ctx->info );   <------- ctx->info often NULL

    mbedtls_zeroize( ctx, sizeof( mbedtls_pem_context ) );

Just out of interest, I see that a typical secure handshake requires more that 20'000 mbedtls_calloc(), mbedtls_free() call pairs to be executed!!!!!



Dec 18, 2017 08:59
Ron Eldor

Hi Mark,
As mentioned in the C standard, section

If ptr is a null pointer, no action occurs.

This means that free() can accept a NULL pointer, and should ignore it. According to the C standard, you shouldn't add extra dummy code, checking for NULL pointer, when you want to free a memory.
Al.locating a dummy memory, just for it to be freed later, is bad practice. Depending on the Memory Management, it can result in memory fragmentation; in addition, having memory allocated for no real use, is wasteful, especially in a memory constraint environment.
Mbed TLS Team member