glib-aux: fix nm_str_buf_finalize() for cloning buffer

NMStrBuf can also contains NUL characters. We thus cannot use g_strndup(),
which uses strncpy() and truncates at the first NUL.

Fixes: 13d25f9d0b ('glib-aux: add support for starting with stack-allocated buffer in NMStrBuf')
This commit is contained in:
Thomas Haller 2022-09-29 08:18:42 +02:00
parent 786bb9d048
commit 520411623d
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 14 additions and 1 deletions

View file

@ -530,7 +530,10 @@ nm_str_buf_finalize(NMStrBuf *strbuf, gsize *out_len)
char *str = g_steal_pointer(&strbuf->_priv_str);
char *result;
result = g_strndup(str, strbuf->_priv_len);
result = g_new(char, strbuf->_priv_len + 1u);
memcpy(result, str, strbuf->_priv_len);
result[strbuf->_priv_len] = '\0';
if (strbuf->_priv_do_bzero_mem)
nm_explicit_bzero(str, strbuf->_priv_len);
return result;

View file

@ -974,6 +974,16 @@ test_nm_str_buf(void)
} else
g_assert(stack_buf != nm_str_buf_get_str(&strbuf));
}
{
nm_auto_str_buf NMStrBuf s1 = NM_STR_BUF_INIT_A(10, nmtst_get_rand_bool());
gs_free char *str = NULL;
gsize l;
nm_str_buf_append_len(&s1, "a\0b", 3);
str = nm_str_buf_finalize(&s1, &l);
g_assert_cmpmem(str, l + 1, "a\0b", 4);
}
}
/*****************************************************************************/