diff --git a/libavformat/ffm.c b/libavformat/ffm.c
index 89764c349737984019d234e26d92dd0eddd2fdd3..ce18d5fe9a665e869f99e47a0e39514ced1bcd75 100644
--- a/libavformat/ffm.c
+++ b/libavformat/ffm.c
@@ -278,8 +278,6 @@ static int ffm_write_trailer(AVFormatContext *s)
         put_flush_packet(pb);
     }
 
-    for(i=0;i<s->nb_streams;i++)
-        av_freep(&s->streams[i]->priv_data);
     return 0;
 }
 #endif //CONFIG_ENCODERS
diff --git a/libavformat/mpeg.c b/libavformat/mpeg.c
index 1208880d0e62876630a91426768b04e7cbffc0f9..38ae418fd616dae28373f778e6c45c723b4f80cc 100644
--- a/libavformat/mpeg.c
+++ b/libavformat/mpeg.c
@@ -1012,9 +1012,6 @@ static int mpeg_mux_end(AVFormatContext *ctx)
     //put_be32(&ctx->pb, ISO_11172_END_CODE);
     //put_flush_packet(&ctx->pb);
 
-    for(i=0;i<ctx->nb_streams;i++)
-        av_freep(&ctx->streams[i]->priv_data);
-
     return 0;
 }
 #endif //CONFIG_ENCODERS
diff --git a/libavformat/utils.c b/libavformat/utils.c
index a6a823b6c53dfd2d2d0e0bb600a35a6d4ab93905..c1ac6d14b45f963289c812ec74a6ae932405f31c 100644
--- a/libavformat/utils.c
+++ b/libavformat/utils.c
@@ -2094,13 +2094,13 @@ int av_interleaved_write_frame(AVFormatContext *s, AVPacket *pkt){
  * @return 0 if OK. AVERROR_xxx if error.  */
 int av_write_trailer(AVFormatContext *s)
 {
-    int ret;
+    int ret, i;
     
     for(;;){
         AVPacket pkt;
         ret= av_interleave_packet(s, &pkt, NULL, 1);
         if(ret<0) //FIXME cleanup needed for ret<0 ?
-            return ret;
+            goto fail;
         if(!ret)
             break;
         
@@ -2110,10 +2110,13 @@ int av_write_trailer(AVFormatContext *s)
         av_free_packet(&pkt);
         
         if(ret<0)
-            return ret; 
+            goto fail;
     }
 
     ret = s->oformat->write_trailer(s);
+fail:
+    for(i=0;i<s->nb_streams;i++)
+        av_freep(&s->streams[i]->priv_data);
     av_freep(&s->priv_data);
     return ret;
 }