diff --git a/libavformat/aviobuf.c b/libavformat/aviobuf.c
index 5064eb826b35cc495585721fcca340c12c8d6b3e..0024f9e8b22e093190c5fdb79d4995f8bedc7b1d 100644
--- a/libavformat/aviobuf.c
+++ b/libavformat/aviobuf.c
@@ -964,6 +964,11 @@ int avio_close_dyn_buf(AVIOContext *s, uint8_t **pbuffer)
     static const char padbuf[FF_INPUT_BUFFER_PADDING_SIZE] = {0};
     int padding = 0;
 
+    if (!s) {
+        *pbuffer = NULL;
+        return 0;
+    }
+
     /* don't attempt to pad fixed-size packet buffers */
     if (!s->max_packet_size) {
         avio_write(s, padbuf, sizeof(padbuf));