diff --git a/libavformat/metadata.c b/libavformat/metadata.c
index 6744f22db7f9f62389b3394b2f918e74d218761a..1a2a907d980803d6731324cf60767269d24ad122 100644
--- a/libavformat/metadata.c
+++ b/libavformat/metadata.c
@@ -68,8 +68,10 @@ int av_metadata_set(AVMetadata **pm, const char *key, const char *value)
         m->elems[m->count].value= av_strdup(value);
         m->count++;
     }
-    if(!m->count)
+    if(!m->count) {
+        av_free(m->elems);
         av_freep(pm);
+    }
 
     return 0;
 }