diff --git a/libavutil/opt.c b/libavutil/opt.c
index 2cc6f6ce344027877a814bcfc6c044b038fc734f..f2b947337e9a3e4b33b4652d35415b6105e49cf0 100644
--- a/libavutil/opt.c
+++ b/libavutil/opt.c
@@ -562,9 +562,16 @@ static int parse_key_value_pair(void *ctx, const char **buf,
     char *val;
     int ret;
 
+    if (!key)
+        return AVERROR(ENOMEM);
+
     if (*key && strspn(*buf, key_val_sep)) {
         (*buf)++;
         val = av_get_token(buf, pairs_sep);
+        if (!val) {
+            av_freep(&key);
+            return AVERROR(ENOMEM);
+        }
     } else {
         av_log(ctx, AV_LOG_ERROR, "Missing key or no key/value separator found after key '%s'\n", key);
         av_free(key);