diff --git a/libavformat/mpegtsenc.c b/libavformat/mpegtsenc.c
index 5c0b0d761e..5ecc7fb447 100644
--- a/libavformat/mpegtsenc.c
+++ b/libavformat/mpegtsenc.c
@@ -623,8 +623,8 @@ static int mpegts_write_header(AVFormatContext *s)
 
     pids = av_malloc_array(s->nb_streams, sizeof(*pids));
     if (!pids) {
-        av_free(service);
-        return AVERROR(ENOMEM);
+        ret = AVERROR(ENOMEM);
+        goto fail;
     }
 
     /* assign pids to each stream */