Skip to content

Commit 67761be

Browse files
committed
Merge branch 'rj/strvec-splice-fix'
Correct strvec_splice() that misbehaved when the strvec is empty. * rj/strvec-splice-fix: strvec: `strvec_splice()` to a statically initialized vector
2 parents e6663b9 + 14ef8c0 commit 67761be

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

strvec.c

+7-4
Original file line numberDiff line numberDiff line change
@@ -61,16 +61,19 @@ void strvec_splice(struct strvec *array, size_t idx, size_t len,
6161
{
6262
if (idx + len > array->nr)
6363
BUG("range outside of array boundary");
64-
if (replacement_len > len)
64+
if (replacement_len > len) {
65+
if (array->v == empty_strvec)
66+
array->v = NULL;
6567
ALLOC_GROW(array->v, array->nr + (replacement_len - len) + 1,
6668
array->alloc);
69+
array->v[array->nr + (replacement_len - len)] = NULL;
70+
}
6771
for (size_t i = 0; i < len; i++)
6872
free((char *)array->v[idx + i]);
69-
if (replacement_len != len) {
73+
if ((replacement_len != len) && array->nr)
7074
memmove(array->v + idx + replacement_len, array->v + idx + len,
7175
(array->nr - idx - len + 1) * sizeof(char *));
72-
array->nr += (replacement_len - len);
73-
}
76+
array->nr += replacement_len - len;
7477
for (size_t i = 0; i < replacement_len; i++)
7578
array->v[idx + i] = xstrdup(replacement[i]);
7679
}

t/unit-tests/strvec.c

+10
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,16 @@ void test_strvec__pushv(void)
8888
strvec_clear(&vec);
8989
}
9090

91+
void test_strvec__splice_just_initialized_strvec(void)
92+
{
93+
struct strvec vec = STRVEC_INIT;
94+
const char *replacement[] = { "foo" };
95+
96+
strvec_splice(&vec, 0, 0, replacement, ARRAY_SIZE(replacement));
97+
check_strvec(&vec, "foo", NULL);
98+
strvec_clear(&vec);
99+
}
100+
91101
void test_strvec__splice_with_same_size_replacement(void)
92102
{
93103
struct strvec vec = STRVEC_INIT;

0 commit comments

Comments
 (0)