简单的ffmpeg程序存在内存泄漏

Simple ffmpeg program has memory leaks

环境:Ubuntu14.04

我在 http://dranger.com/ffmpeg/tutorial01.html 编译了来自 ffmpeg 教程第 1 步的简单源代码。当我通过 valgrind 运行 二进制文件时,它报告了一堆内存泄漏。这是一个例子:

==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)

这是来自 test1.cpp 第 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
 }

在主函数 returns 之前,它确实关闭了上下文:

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

是否需要执行其他操作以确保正确释放内存?

有兴趣的可以到我说的link下载源文件。问候。

docsavcodec_alloc_context3

The resulting struct should be freed with avcodec_free_context().

添加 avcodec_free_context(&pCodecCtx); 看看它是否适合你。

隐藏在libav 11.3的源代码中,avprobe.c定义了正确关闭输入文件的有用方法:


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);
}

这个清理了几乎所有的内存泄漏。