refactor: add xmemcpyz() and use it in place of some xstrlcpy() (#28422)

Problem:  Using xstrlcpy() when the exact length of the string to be
          copied is known is not ideal because it requires adding 1 to
          the length and an unnecessary strlen().
Solution: Add xmemcpyz() and use it in place of such xstrlcpy() calls.
This commit is contained in:
zeertzjq
2024-04-20 19:31:00 +08:00
committed by GitHub
parent 4d52b0cf67
commit 0ea38c9a53
23 changed files with 61 additions and 46 deletions

View File

@@ -202,7 +202,7 @@ void *xmallocz(size_t size)
}
void *ret = xmalloc(total_size);
((char *)ret)[size] = 0;
((char *)ret)[size] = '\0';
return ret;
}
@@ -222,6 +222,21 @@ void *xmemdupz(const void *data, size_t len)
return memcpy(xmallocz(len), data, len);
}
/// Duplicates `len` bytes of `src` to `dst` and zero terminates it.
/// and returns a pointer to the allocated memory. If the allocation fails,
/// the program dies.
///
/// @see {xstrlcpy}
/// @param[out] dst Buffer to store the result.
/// @param[in] src Buffer to be copied.
/// @param[in] len Number of bytes to be copied.
void *xmemcpyz(void *dst, const void *src, size_t len)
{
memcpy(dst, src, len);
((char *)dst)[len] = '\0';
return dst;
}
#ifndef HAVE_STRNLEN
size_t xstrnlen(const char *s, size_t n)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_PURE