vasprintf.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /*
  2. * libcompat - system compatibility library
  3. *
  4. * Copyright © 2010 Guillem Jover <guillem@debian.org>
  5. *
  6. * This is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. #include <config.h>
  20. #include <stdarg.h>
  21. #include <stdio.h>
  22. #include <stdlib.h>
  23. #include "compat.h"
  24. int
  25. vasprintf(char **strp, char const *fmt, va_list args)
  26. {
  27. va_list args_copy;
  28. int needed, n;
  29. char *str;
  30. va_copy(args_copy, args);
  31. needed = vsnprintf(NULL, 0, fmt, args_copy);
  32. va_end(args_copy);
  33. if (needed < 0) {
  34. *strp = NULL;
  35. return -1;
  36. }
  37. str = malloc(needed + 1);
  38. if (str == NULL) {
  39. *strp = NULL;
  40. return -1;
  41. }
  42. n = vsnprintf(str, needed + 1, fmt, args);
  43. if (n < 0) {
  44. free(str);
  45. str = NULL;
  46. }
  47. *strp = str;
  48. return n;
  49. }