From: Lennart Poettering Date: Tue, 16 Jan 2024 18:15:34 +0000 (+0100) Subject: strv: modernize strv_insert() X-Git-Tag: v256-rc1~1126^2~6 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=a43431067e0129bc2b9923c17c88fe515307dd6b;p=thirdparty%2Fsystemd.git strv: modernize strv_insert() Let's use memmove() to move the string contents, rather than manual loops. Fix the overflow extension. Prefer reallocarray() over malloc() --- diff --git a/src/basic/strv.c b/src/basic/strv.c index fa17631aa0e..27a70a84158 100644 --- a/src/basic/strv.c +++ b/src/basic/strv.c @@ -505,29 +505,31 @@ int strv_insert(char ***l, size_t position, char *value) { char **c; size_t n, m; + assert(l); + if (!value) return 0; n = strv_length(*l); position = MIN(position, n); - /* increase and check for overflow */ - m = n + 2; - if (m < n) + /* check for overflow and increase*/ + if (n > SIZE_MAX - 2) return -ENOMEM; + m = n + 2; - c = new(char*, m); + c = reallocarray(*l, GREEDY_ALLOC_ROUND_UP(m), sizeof(char*)); if (!c) return -ENOMEM; - for (size_t i = 0; i < position; i++) - c[i] = (*l)[i]; + if (n > position) + memmove(c + position + 1, c + position, (n - position) * sizeof(char*)); + c[position] = value; - for (size_t i = position; i < n; i++) - c[i+1] = (*l)[i]; - c[n+1] = NULL; + c[n + 1] = NULL; - return free_and_replace(*l, c); + *l = c; + return 0; } int strv_consume_with_size(char ***l, size_t *n, char *value) {