From 392d1246213ca4a5f1cd16881db148fa884577fd Mon Sep 17 00:00:00 2001 From: 0z5a Date: Wed, 18 Nov 2026 16:03:10 +0100 Subject: [PATCH] libvmaf/dict: don't grow the entry array when overwriting a key vmaf_dictionary_set() looks up an existing entry before it grows the array. When the dictionary is full (cnt == size) and the key already exists, realloc() can move the array and existing_entry then points into freed memory: the new value is written there and the old value is freed a second time when the dictionary is destroyed. Only grow the array when a new entry is appended. Overwriting a key never needs more space. The HDR-VMAF v1.1.8 models carry exactly eight adm options, so overriding any of them (e.g. adm.adm_enhn_gain_limit=1.0 on the command line) hits this on the first overload. --- libvmaf/src/dict.c | 2 +- libvmaf/test/test_dict.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/libvmaf/src/dict.c b/libvmaf/src/dict.c index 8c1f3a3186..b4c5547a2f 100644 --- a/libvmaf/src/dict.c +++ b/libvmaf/src/dict.c @@ -69,7 +69,7 @@ int vmaf_dictionary_set(VmafDictionary **dict, const char *key, const char *val, return ret; } - if (d->cnt == d->size) { + if (!existing_entry && d->cnt == d->size) { const size_t sz = d->size * sizeof(*d->entry) * 2; VmafDictionaryEntry *entry = realloc(d->entry, sz); if (!entry) goto fail; diff --git a/libvmaf/test/test_dict.c b/libvmaf/test/test_dict.c index 39e39c19d6..7ffda1ac86 100644 --- a/libvmaf/test/test_dict.c +++ b/libvmaf/test/test_dict.c @@ -379,9 +379,40 @@ static char *test_isnumeric() return NULL; } +static char *test_vmaf_dictionary_overwrite_when_full() +{ + int err = 0; + + VmafDictionary *dict = NULL; + char key[16], val[16]; + for (unsigned i = 0; i < 8; i++) { + snprintf(key, sizeof(key), "key_%u", i); + snprintf(val, sizeof(val), "val_%u", i); + err |= vmaf_dictionary_set(&dict, key, val, 0); + } + mu_assert("problem during vmaf_dictionary_set", !err); + mu_assert("dictionary should be completely full", + dict->size == 8 && dict->cnt == 8); + + err = vmaf_dictionary_set(&dict, "key_3", "new_val", 0); + mu_assert("problem during vmaf_dictionary_set", !err); + mu_assert("overwrite should not add an entry", dict->cnt == 8); + mu_assert("overwrite should not grow the dictionary", dict->size == 8); + const VmafDictionaryEntry *e = vmaf_dictionary_get(&dict, "key_3", 0); + mu_assert("overwritten key should be present", e); + mu_assert("overwritten key should have the new value", + !strcmp(e->val, "new_val")); + + err = vmaf_dictionary_free(&dict); + mu_assert("problem during vmaf_dictionary_free", !err); + + return NULL; +} + char *run_tests() { mu_run_test(test_vmaf_dictionary); + mu_run_test(test_vmaf_dictionary_overwrite_when_full); mu_run_test(test_vmaf_dictionary_merge); mu_run_test(test_vmaf_dictionary_compare); mu_run_test(test_vmaf_dictionary_normalize_numerical_val);