asprintf.c 790 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include <stdarg.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include "asprintf.h"
  5. /**
  6. * asprintf(ret, format, ...):
  7. * Do asprintf(3) like GNU and BSD do.
  8. */
  9. int
  10. asprintf(char ** ret, const char * format, ...)
  11. {
  12. va_list ap;
  13. int len;
  14. size_t buflen;
  15. /* Figure out how long the string needs to be. */
  16. va_start(ap, format);
  17. len = vsnprintf(NULL, 0, format, ap);
  18. va_end(ap);
  19. /* Did we fail? */
  20. if (len < 0)
  21. goto err0;
  22. buflen = (size_t)(len) + 1;
  23. /* Allocate memory. */
  24. if ((*ret = malloc(buflen)) == NULL)
  25. goto err0;
  26. /* Actually generate the string. */
  27. va_start(ap, format);
  28. len = vsnprintf(*ret, buflen, format, ap);
  29. va_end(ap);
  30. /* Did we fail? */
  31. if (len < 0)
  32. goto err1;
  33. /* Success! */
  34. return (len);
  35. err1:
  36. free(*ret);
  37. err0:
  38. /* Failure! */
  39. return (-1);
  40. }