From fd051a19d9fdae1c31b07a9d35be905a1d83bc25 Mon Sep 17 00:00:00 2001 From: Alejandro Colomar Date: Thu, 23 Nov 2023 01:06:52 +0100 Subject: [PATCH] lib/: Use NITEMS() instead of SIZEOF_ARRAY() where number of elements is meant For arrays of char, both NITEMS() and SIZEOF_ARRAY() return the same value. However, NITEMS() is more appropriate. Think of wide-character equivalents of the same code; with NITEMS(), they would continue to be valid, while with SIZEOF_ARRAY(), they would be wrong. In the implementation of ZUSTR2STP(), we want SIZEOF_ARRAY() within the static assert, because we're just comparing the sizes of the source and destination buffers, and we don't care if we compare sizes or numbers of elements, and using sizes is just simpler. But we want NITEMS() in the zustr2stp() call, where we want to copy a specific number of characters. Signed-off-by: Alejandro Colomar --- lib/strtcpy.h | 4 ++-- lib/utmp.c | 2 +- lib/zustr2stp.h | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/strtcpy.h b/lib/strtcpy.h index 60f44f9f1..25255493a 100644 --- a/lib/strtcpy.h +++ b/lib/strtcpy.h @@ -31,7 +31,7 @@ * at the buffer pointed to by dst. If the destination buffer, * isn't large enough to hold the copy, the resulting string is * truncated. The size of the buffer is calculated internally via - * SIZEOF_ARRAY(). + * NITEMS(). * * RETURN VALUE * -1 If this call truncated the resulting string. @@ -44,7 +44,7 @@ */ -#define STRTCPY(dst, src) strtcpy(dst, src, SIZEOF_ARRAY(dst)) +#define STRTCPY(dst, src) strtcpy(dst, src, NITEMS(dst)) inline ssize_t strtcpy(char *restrict dst, const char *restrict src, diff --git a/lib/utmp.c b/lib/utmp.c index 7f116f3b7..bf878ce6b 100644 --- a/lib/utmp.c +++ b/lib/utmp.c @@ -246,7 +246,7 @@ static #ifdef HAVE_STRUCT_UTMP_UT_HOST } else if ( (NULL != ut) && ('\0' != ut->ut_host[0])) { - hostname = XMALLOC(SIZEOF_ARRAY(ut->ut_host) + 1, char); + hostname = XMALLOC(NITEMS(ut->ut_host) + 1, char); ZUSTR2STP(hostname, ut->ut_host); #endif /* HAVE_STRUCT_UTMP_UT_HOST */ } diff --git a/lib/zustr2stp.h b/lib/zustr2stp.h index 2160a1b0a..436f47bcb 100644 --- a/lib/zustr2stp.h +++ b/lib/zustr2stp.h @@ -22,7 +22,7 @@ ({ \ static_assert(!is_array(dst) || sizeof(dst) > SIZEOF_ARRAY(src), ""); \ \ - zustr2stp(dst, src, SIZEOF_ARRAY(src)); \ + zustr2stp(dst, src, NITEMS(src)); \ }) @@ -62,9 +62,9 @@ inline char *zustr2stp(char *restrict dst, const char *restrict src, size_t sz); * * EXAMPLES * char src[13] = "Hello, world!" // No '\0' in this buffer! - * char dst[SIZEOF_ARRAY(src) + 1]; + * char dst[NITEMS(src) + 1]; * - * zustr2stp(dst, src, SIZEOF_ARRAY(src)); + * zustr2stp(dst, src, NITEMS(src)); * puts(dst); */