[FFmpeg-devel] avformat_new_stream memory leak

Geek.Song ffmpeg at gmail.com
Wed Sep 4 03:03:28 CEST 2013


On Wed, Sep 4, 2013 at 5:45 AM, Jose Santiago <jsantiago at fastmail.us> wrote:

> I created a ticket for this issue https://ffmpeg.org/trac/**
> ffmpeg/ticket/2937 <https://ffmpeg.org/trac/ffmpeg/ticket/2937> and they
> asked me to send this to the ffmpeg-devel list. I have attached a patch to
> fix this issue.
>
> Here is the original issue description:
>
> avformat_new_stream() calls avcodec_alloc_context3() which can allocate
> data that is not free'd by the manual freeing of the codec context done by
> ff_free_stream() which is called by avformat_free_context(). In particular
> the st->codec->priv_data is allocated, but not free'd. The attached patch
> modifies ff_free_stream() to call avcodec_close() to properly close the
> codec context allocated in avformat_new_stream() .
>
>

In normal scenario, you should close the codec firstly before calling
av_format_free_context() if you have succeeded in opening the codec by
calling avcodec_open2().



> For instance in the following code:
>
> AVFormatContext * formatCtx;
> AVCodec * codec;
> AVStream * avStream;
> AVOutputFormat * outputFormat;
> const char * shortName = "mpegts";
> const char * outputURL = "file://somefile.ts";
>
> outputFormat = av_guess_format(shortName, outputURL, NULL);
> assert(outputFormat != NULL);
> avformat_alloc_output_**context2(&formatCtx, outputFormat, shortName,
> outputURL);
> assert(formatCtx != NULL);
> avio_open2(&formatCtx->pb, outputURL, AVIO_FLAG_WRITE, NULL, NULL);
> codec = avcodec_find_decoder(AV_CODEC_**ID_H264);
> assert(codec != NULL);
> avStream = avformat_new_stream(formatCtx, codec);
> assert(avStream != NULL);
> avformat_write_header(**formatCtx, NULL);
> av_write_trailer(formatCtx);
> avio_close(formatCtx->pb);
> formatCtx->pb = NULL;
> # Not all of the st[]->codec is free'd here.
> avformat_free_context(**formatCtx);
>
> --
-----------------------------------------------------------------------------------------
My key fingerprint: d1:03:f5:32:26:ff:d7:3c:e4:42:e3:51:ec:92:78:b2


More information about the ffmpeg-devel mailing list