diff --git a/avconv.c b/avconv.c
index cce9a83e6a54d308942837d0ddba0ecba22ad39b..480823506f0a41ec355d6424b944aeef291461b1 100644
--- a/avconv.c
+++ b/avconv.c
@@ -167,7 +167,7 @@ static void exit_program(void)
     /* close files */
     for (i = 0; i < nb_output_files; i++) {
         AVFormatContext *s = output_files[i]->ctx;
-        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)
+        if (s && s->oformat && !(s->oformat->flags & AVFMT_NOFILE) && s->pb)
             avio_close(s->pb);
         avformat_free_context(s);
         av_dict_free(&output_files[i]->opts);