diff mbox series

[FFmpeg-devel,11/11] avutil/opt: Avoid av_strdup(NULL)

Message ID GV1P250MB07372251A5266F5F95ED1D9F8F362@GV1P250MB0737.EURP250.PROD.OUTLOOK.COM
State Accepted
Commit aa7d6520e6335f9ed45ca2bf0fbf932fb4b2dea6
Headers show
Series [FFmpeg-devel,01/10] doc/examples: Always use <> includes | expand

Checks

Context Check Description
yinshiyou/make_loongarch64 success Make finished
yinshiyou/make_fate_loongarch64 fail Make fate failed
andriy/make_x86 success Make finished
andriy/make_fate_x86 fail Make fate failed

Commit Message

Andreas Rheinhardt March 25, 2024, 12:56 p.m. UTC
It is not documented to be safe and in any case it is nonsense:
Currently av_strdup(NULL) returns NULL and in order to distinguish
this from a genuine allocation failure, opt_copy_elem()
checked afterwards whether src was actually NULL. But then one
can simply check in advance whether one should call av_strdup()
at all.
set_string() was even worse and returned ENOMEM in case the value
to be duplicated is NULL; this only worked because
av_opt_set_defaults2() does not check the return value at all
(given that it can't propagate it).

These two places account for 389114 of 390356 av_strdup(NULL)
calls during one FATE run.

Signed-off-by: Andreas Rheinhardt <andreas.rheinhardt@outlook.com>
---
 libavutil/opt.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
diff mbox series

Patch

diff --git a/libavutil/opt.c b/libavutil/opt.c
index 76080f87e8..3130606337 100644
--- a/libavutil/opt.c
+++ b/libavutil/opt.c
@@ -309,6 +309,8 @@  static int set_string_binary(void *obj, const AVOption *o, const char *val, uint
 static int set_string(void *obj, const AVOption *o, const char *val, uint8_t **dst)
 {
     av_freep(dst);
+    if (!val)
+        return 0;
     *dst = av_strdup(val);
     return *dst ? 0 : AVERROR(ENOMEM);
 }
@@ -2032,9 +2034,11 @@  static int opt_copy_elem(void *logctx, enum AVOptionType type,
     if (type == AV_OPT_TYPE_STRING) {
         if (*dst8 != *src8)
             av_freep(dst8);
-        *dst8 = av_strdup(*src8);
-        if (*src8 && !*dst8)
-            return AVERROR(ENOMEM);
+        if (*src8) {
+            *dst8 = av_strdup(*src8);
+            if (!*dst8)
+                return AVERROR(ENOMEM);
+        }
     } else if (type == AV_OPT_TYPE_BINARY) {
         int len = *(const int *)(src8 + 1);
         if (*dst8 != *src8)