diff --git a/ffmpeg_hw.c b/ffmpeg_hw.c
index 5708e9af20789d08a95e99e574eb4d18b0fec1c6..a4d1cada591edcd908a21930ca6090a6623c4cf6 100644
--- a/ffmpeg_hw.c
+++ b/ffmpeg_hw.c
@@ -77,7 +77,7 @@ int hw_device_init_from_string(const char *arg, HWDevice **dev_out)
     char *type_name = NULL, *name = NULL, *device = NULL;
     enum AVHWDeviceType type;
     HWDevice *dev, *src;
-    AVBufferRef *device_ref;
+    AVBufferRef *device_ref = NULL;
     int err;
     const char *errmsg, *p, *q;
     size_t k;
@@ -210,6 +210,7 @@ invalid:
 fail:
     av_log(NULL, AV_LOG_ERROR,
            "Device creation failed: %d.\n", err);
+    av_buffer_unref(&device_ref);
     goto done;
 }