]> git.ipfire.org Git - thirdparty/shadow.git/commitdiff
lib/strncpy.h: Add STRNCPY() wrapper for strncpy(3)
authorAlejandro Colomar <alx@kernel.org>
Wed, 15 Nov 2023 21:31:02 +0000 (22:31 +0100)
committerSerge Hallyn <serge@hallyn.com>
Sun, 26 Nov 2023 12:48:18 +0000 (06:48 -0600)
This wrapper calculates the destination buffer's size, to avoid errors
in the size calculation.

A curious fact: this macro did exist in Version 7 Unix (with a slightly
different name).  I found it by chance, investigating the origins of
strncpy(3) and strncat(3) in V7, after Branden suggested me to do so,
related to recent discussions about string_copying(7).

alx@debian:~/src/unix/unix/Research-V7$ grepc SCPYN .
./usr/src/cmd/login.c:#define SCPYN(a, b) strncpy(a, b, sizeof(a))

Our implementation is slightly better, because using nitems() we're
protected against passing a pointer instead of an array, and it's also
conceptually more appropriate: for wide characters, it would be

#define WCSNCPY(dst, src)  wcsncpy(dst, src, NITEMS(dst))

Cc: "G. Branden Robinson" <branden@debian.org>
Signed-off-by: Alejandro Colomar <alx@kernel.org>
lib/Makefile.am
lib/strncpy.h [new file with mode: 0644]

index 96dfefe2e775fc98141af6d9061a3245d81d7482..bfe13c33ba30a6eed65a7f4de6bcb5458098cb57 100644 (file)
@@ -141,6 +141,7 @@ libshadow_la_SOURCES = \
        stpecpy.h \
        stpeprintf.c \
        stpeprintf.h \
+       strncpy.h \
        strtcpy.c \
        strtcpy.h \
        strtoday.c \
diff --git a/lib/strncpy.h b/lib/strncpy.h
new file mode 100644 (file)
index 0000000..fc6fcc9
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * SPDX-FileCopyrightText: 2023, Alejandro Colomar <alx@kernel.org>
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+
+
+#ifndef SHADOW_INCLUDE_LIB_STRNCPY_H_
+#define SHADOW_INCLUDE_LIB_STRNCPY_H_
+
+
+#include <config.h>
+
+#include <string.h>
+
+#include "sizeof.h"
+
+
+#define STRNCPY(dst, src)  strncpy(dst, src, NITEMS(dst))
+
+
+#endif  // include guard