strlcpy.c 1.6 KB

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