Specifically I'm looking at avformat_free_context
. In normal execution of my code, avformat_free_context
is called appropriately. I would also like to call it in the destructor of a class, in case there was an exceptional case that caused the code using the AVFormatContext
to return early. Do the ffmpeg free functions behave appropriately when called on already freed data structures?
Links are to function definitions; see for yourself!
av_freep
avformat_free_context
calls av_freep
on some pointers held by the AVFormatContext
which doesn't perform a NULL
check before passing the address of the memory to be freed off to av_free
(which is essentially just a call to free
; see below). It does, however, set the pointer to NULL.
av_free
If ffmpeg was compiled with CONFIG_MEMALIGN_HACK
defined, av_free
will do a NULL check before freeing. This will effectively make av_freep
idempotent for memory which is freed by av_freep(&pointer_to_data);
. This might not be the case for your build.
others
Additionally, some of the other functions called by avformat_free_context
are idempotent. They achieve this by clearing pointers and performing NULL checks, or decreasing array indexes to prevent a double free. Examples include ff_free_stream
and av_opt_free
.
avformat_free_context
avformat_free_context
will perform a NULL check before attempting to free the context. So if you pass NULL to it, you don't have to worry. However, if you double-free an AVFormatContext
you will end up doing a low-level double-free, because avformat_free_context
calls av_free
directly on the AVFormatContext
.
The safest thing to do when freeing a context is:
avformat_free_context(pcontext);
pcontext = NULL;