1/* Copy a null-terminated string to a fixed-size buffer, with length checking.
2 Copyright (C) 2023-2024 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <https://www.gnu.org/licenses/>. */
18
19#include <string.h>
20
21size_t
22__strlcpy (char *__restrict dest, const char *__restrict src, size_t size)
23{
24 size_t src_length = strlen (src);
25
26 if (__glibc_unlikely (src_length >= size))
27 {
28 if (size > 0)
29 {
30 /* Copy the leading portion of the string. The last
31 character is subsequently overwritten with the NUL
32 terminator, but the destination size is usually a
33 multiple of a small power of two, so writing it twice
34 should be more efficient than copying an odd number of
35 bytes. */
36 memcpy (dest, src, size);
37 dest[size - 1] = '\0';
38 }
39 }
40 else
41 /* Copy the string and its terminating NUL character. */
42 memcpy (dest, src, src_length + 1);
43 return src_length;
44}
45libc_hidden_def (__strlcpy)
46weak_alias (__strlcpy, strlcpy)
47

source code of glibc/string/strlcpy.c