Search code examples
clibavformat

AVFormat lib avformat_free_context


i try this code to get duration of a media file:

AVFormatContext* pFormatCtx = NULL;
avformat_open_input(&pFormatCtx, filename.c_str(), NULL, NULL);

if (pFormatCtx != 0) {
    avformat_find_stream_info(pFormatCtx, NULL);

    int64_t media_duration = pFormatCtx->duration;
    duration = media_duration/AV_TIME_BASE;

    avformat_close_input(&pFormatCtx);
    avformat_free_context(pFormatCtx);
}

The problem is if i call avformat_free_context() the app die, if i comment out the line the program works, but i prefer to avoid memory leak.

PS: i call av_register_all() when the program start.


Solution

  • Because avformat_close_input will free the AVFormatContext after it close it. That is why you should send pFormatCtx by pointer.

    So you don't need to call avformat_free_context as it is already called by avformat_close_input and no need to worry about memory leaks.

    See the documentation for avformat_close_input for reference.