libio: Improve fortify with clang
[glibc.git] / string / strlcpy.c
blobc6c33b1e33d601c66776ea6eec1b0c8f8ed696a9
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.
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.
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.
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/>. */
19 #include <string.h>
21 size_t
22 __strlcpy (char *__restrict dest, const char *__restrict src, size_t size)
24 size_t src_length = strlen (src);
26 if (__glibc_unlikely (src_length >= size))
28 if (size > 0)
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';
40 else
41 /* Copy the string and its terminating NUL character. */
42 memcpy (dest, src, src_length + 1);
43 return src_length;
45 libc_hidden_def (__strlcpy)
46 weak_alias (__strlcpy, strlcpy)