vsnprintf.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Formatted output to strings.
  2. Copyright (C) 2004, 2006-2021 Free Software Foundation, Inc.
  3. Written by Simon Josefsson and Yoann Vandoorselaere <yoann@prelude-ids.org>.
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2, or (at your option)
  7. any later version.
  8. This program 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
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, see <https://www.gnu.org/licenses/>. */
  14. #ifdef HAVE_CONFIG_H
  15. # include <config.h>
  16. #endif
  17. /* Specification. */
  18. #include <stdio.h>
  19. #include <errno.h>
  20. #include <limits.h>
  21. #include <stdarg.h>
  22. #include <stdlib.h>
  23. #include <string.h>
  24. #include "vasnprintf.h"
  25. /* Print formatted output to string STR. Similar to vsprintf, but
  26. additional length SIZE limit how much is written into STR. Returns
  27. string length of formatted string (which may be larger than SIZE).
  28. STR may be NULL, in which case nothing will be written. On error,
  29. return a negative value. */
  30. int
  31. vsnprintf (char *str, size_t size, const char *format, va_list args)
  32. {
  33. char *output;
  34. size_t len;
  35. size_t lenbuf = size;
  36. output = vasnprintf (str, &lenbuf, format, args);
  37. len = lenbuf;
  38. if (!output)
  39. return -1;
  40. if (output != str)
  41. {
  42. if (size)
  43. {
  44. size_t pruned_len = (len < size ? len : size - 1);
  45. memcpy (str, output, pruned_len);
  46. str[pruned_len] = '\0';
  47. }
  48. free (output);
  49. }
  50. if (len > INT_MAX)
  51. {
  52. errno = EOVERFLOW;
  53. return -1;
  54. }
  55. return len;
  56. }