that call attempts to free() uninitialized objects in the mbedtls_ssl_context
There shouldn't be any uninitialized objects ever. So I guess the problem is that you forgot to initialize the context. Whenever you have an mbedtls_xxx
structure, always call the corresponding mbedtls_xxx_init()
function before doing anything else.
With two connections and session loading, the code to set up the connections would look something like this.
mbedtls_ssl_config ssl_config;
mbedtls_ssl_config_init(&ssl_config);
mbedtls_ssl_context ssl_context_control, ssl_context_data;
mbedtls_ssl_init(&ssl_context_control);
mbedtls_ssl_init(&ssl_context_data);
int ret;
// prepare ssl_config here
ret = mbedtls_ssl_setup(&ssl_context_control, &ssl_config);
if (ret != 0) goto error;
ret = mbedtls_ssl_setup(&ssl_context_data, &ssl_config);
if (ret != 0) goto error;
if (have_saved_sessions) {
mbedtls_ssl_session ssl_session_control, ssl_session_data;
mbedtls_ssl_session_init(&ssl_session_control);
mbedtls_ssl_session_init(&ssl_session_data);
ret = mbedtls_ssl_session_load(&ssl_session_control, ...);
if (ret != 0) goto session_done;
ret = mbedtls_ssl_session_load(&ssl_session_data, ...);
if (ret != 0) goto session_done;
ret = mbedtls_ssl_set_session(&ssl_context_control, &ssl_session_control);
if (ret != 0) goto session_done;
ret = mbedtls_ssl_set_session(&ssl_context_data, &ssl_session_data);
if (ret != 0) goto session_done;
session_done:
mbedtls_ssl_session_free(&ssl_session_control);
mbedtls_ssl_session_free(&ssl_session_data);
if (ret != 0) goto error;
}
// the contexts are ready for use here
For cleanup, the rule is that each mbedtls_xxx_init()
function has a corresponding mbedtls_xxx_free()
function. Note that the name free
is misleading: these functions clean up the object and free embedded resources (e.g. malloc'ed sub-structures) but they do not free the argument in the sense of heap free()
. If you malloc
or calloc
an mbedtls_xxx
structure, you need to call mbedtls_xxx_free()
and then call free()
. If the mbedtls_xxx
structure is on the stack or global, just call mbedtls_xxx_free()
.
Regarding documentation, the online documentation of Mbed TLS froze at an old version. And even when the version was current, the online documentation is for one specific compile-time configuration with all features enabled. Typeset the documentation for your version and configuration by running make apidoc
in the mbedtls source tree. You need Doxygen (a pretty standard documentation typesetting tool, so it may already be available in your development environment).
TLS is performed using mbedTLS 2.9.0
Beware that this is a very old version which has many unfixed security issues. You should upgrade to 2.28.1 (and keep updating through the 2.28.x long-time support series).