tst-strlcpy.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* Test the strlcpy function.
  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. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <support/check.h>
  19. static int
  20. do_test (void)
  21. {
  22. struct {
  23. char buf1[16];
  24. char buf2[16];
  25. } s;
  26. /* Nothing is written to the destination if its size is 0. */
  27. memset (&s, '@', sizeof (s));
  28. TEST_COMPARE (strlcpy (s.buf1, "Hello!", 0), 6);
  29. TEST_COMPARE_BLOB (&s, sizeof (s), "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@", 32);
  30. /* No bytes are are modified in the target buffer if the source
  31. string is short enough. */
  32. memset (&s, '@', sizeof (s));
  33. TEST_COMPARE (strlcpy (s.buf1, "Hello!", sizeof (s.buf1)), 6);
  34. TEST_COMPARE_BLOB (&s, sizeof (s), "Hello!\0@@@@@@@@@@@@@@@@@@@@@@@@@", 32);
  35. /* A source string which fits exactly into the destination buffer is
  36. not truncated. */
  37. memset (&s, '@', sizeof (s));
  38. TEST_COMPARE (strlcpy (s.buf1, "Hello, world!!!", sizeof (s.buf1)), 15);
  39. TEST_COMPARE_BLOB (&s, sizeof (s),
  40. "Hello, world!!!\0@@@@@@@@@@@@@@@@@@@@@@@@@", 32);
  41. /* A source string one character longer than the destination buffer
  42. is truncated by one character. The untruncated source length is
  43. returned. */
  44. memset (&s, '@', sizeof (s));
  45. TEST_COMPARE (strlcpy (s.buf1, "Hello, world!!!!", sizeof (s.buf1)), 16);
  46. TEST_COMPARE_BLOB (&s, sizeof (s),
  47. "Hello, world!!!\0@@@@@@@@@@@@@@@@@@@@@@@@@", 32);
  48. /* An even longer source string is truncated as well, and the
  49. original length is returned. */
  50. memset (&s, '@', sizeof (s));
  51. TEST_COMPARE (strlcpy (s.buf1, "Hello, world!!!!!!!!", sizeof (s.buf1)), 20);
  52. TEST_COMPARE_BLOB (&s, sizeof (s),
  53. "Hello, world!!!\0@@@@@@@@@@@@@@@@@@@@@@@@@", 32);
  54. return 0;
  55. }
  56. #include <support/test-driver.c>