[Libav-user] AVUtil memory leaks

Jaka Bac jakabac at gmail.com
Mon May 12 12:20:05 EEST 2025


On Mon, 12 May 2025 at 11:02, Tomislav Timic <tomislavtimic98 at gmail.com>
wrote:

> I was observing my application that is doing transcoding of mpegts over
> udp and I noticed that constantly after each create of transcoder pipeline
> and delete of pipeline i get small leaks from avutil.
> [image: Screenshot 2025-05-12 at 11.00.07.png]
> This is how i release input format context
>
> if (formatCtx != nullptr)
> {
>     avformat_close_input(&formatCtx);
>     avformat_free_context(formatCtx);
>     formatCtx = nullptr;
> }
>
> This is how i release decoder
>
> if (frame != nullptr)
> {
>     av_frame_free(&frame);
>     frame = nullptr;
> }
>
> if (videoCodecCtx != nullptr)
> {
>     if (videoCodecCtx->codec != nullptr &&
>         videoCodecCtx->codec->capabilities & AV_CODEC_CAP_ENCODER_FLUSH)
>     {
>         avcodec_flush_buffers(videoCodecCtx);
>     }
>     avcodec_free_context(&videoCodecCtx);
>     videoCodecCtx = nullptr;
> }
>
> if (audioCodecCtx != nullptr)
> {
>     if (audioCodecCtx->codec != nullptr &&
>         audioCodecCtx->codec->capabilities & AV_CODEC_CAP_ENCODER_FLUSH)
>     {
>         avcodec_flush_buffers(audioCodecCtx);
>     }
>     avcodec_free_context(&audioCodecCtx);
>     audioCodecCtx = nullptr;
> }
>
> and this is how i release encoder and muxer
>
> if (codecCtx != nullptr)
> {
>     avcodec_free_context(&codecCtx);
>     codecCtx = nullptr;
> }
>
> if (encodePkt != nullptr)
> {
>     av_packet_free(&encodePkt);
>     encodePkt = nullptr;
> }
>
> if (packet != nullptr)
> {
>     av_packet_free(&packet);
>     packet = nullptr;
> }
>
> for (auto formatCtx: muxFormatCtx)
> {
>     if (formatCtx != nullptr)
>     {
>         av_write_trailer(formatCtx);
>
>         if (!(formatCtx->oformat->flags & AVFMT_NOFILE))
>         {
>             avio_closep(&formatCtx->pb);
>         }
>
>         avformat_free_context(formatCtx);
>         formatCtx = nullptr;
>     }
> }
>
>
There is no need to do both avformat_close_input() and then
avformat_free_context() since avformat_close_input will also free the
context.
avformat_free_context() in your case finds out that it got a null pointer
and doesn't do anything.

As for your leak, how are you opening the output? Maybe you are missing an
avio_closep() ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://ffmpeg.org/pipermail/libav-user/attachments/20250512/83621168/attachment.htm>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: Screenshot 2025-05-12 at 11.00.07.png
Type: image/png
Size: 691804 bytes
Desc: not available
URL: <https://ffmpeg.org/pipermail/libav-user/attachments/20250512/83621168/attachment.png>


More information about the Libav-user mailing list