Peter
Peter

Reputation: 11920

Simple ffmpeg program has memory leaks

Environment: Ubuntu 14.04

I compiled the simple source code from ffmpeg tutorial step 1 at http://dranger.com/ffmpeg/tutorial01.html. When I run the binary through valgrind, it reports a bunch of memory leaks. Here is one example:

==30270== 389,824 bytes in 1 blocks are possibly lost in loss record 8 of 8
==30270==    at 0x4C2D110: memalign (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30270==    by 0x4C2D227: posix_memalign (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==30270==    by 0x9AEDAD: av_malloc (mem.c:81)
==30270==    by 0x9AEEFD: av_mallocz (mem.c:207)
==30270==    by 0x74E70F: avcodec_get_context_defaults3 (options.c:102)i
==30270==    by 0x74E775: avcodec_alloc_context3 (options.c:130)
==30270==    by 0x449737: main (test1.cpp:106)

Here is the snippet from test1.cpp at line 106:

 pCodecCtx = avcodec_alloc_context3(pCodec);
 if(avcodec_copy_context(pCodecCtx, pCodecCtxOrig) != 0) {
    fprintf(stderr, "Couldn't copy codec context");
    return -1; // Error copying codec context
 }

Before the main function returns, it does close the contexts:

 avcodec_close(pCodecCtx);
 avcodec_close(pCodecCtxOrig);
 ...
 return 0;

Is there something else that need to be done to ensure proper memory release?

For those interested, the source file can be downloaded from the link I mentioned. Regards.

Upvotes: 0

Views: 2395

Answers (2)

Peter
Peter

Reputation: 11920

Hidden in the source code of libav 11.3, avprobe.c defines a useful method to properly close the input file:


static void close_input_file(AVFormatContext **ctx_ptr)
{
    int i;
    AVFormatContext *fmt_ctx = *ctx_ptr;

    /* close decoder for each stream */
    for (i = 0; i nb_streams; i++) {
        AVStream *stream = fmt_ctx->streams[i];

        avcodec_close(stream->codec);
    }
    avformat_close_input(ctx_ptr);
}

This one cleans up almost all of the memory leaks.

Upvotes: 1

Maxito
Maxito

Reputation: 629

From the docs about avcodec_alloc_context3

The resulting struct should be freed with avcodec_free_context().

Add avcodec_free_context(&pCodecCtx); and see if it works for you.

Upvotes: 3

Related Questions