sprintf_alloc.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /* sprintf_alloc.c -- like sprintf with memory allocation
  2. Copyright (C) 2010 Ubiq Technologies <graham.gower@gmail.com>
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. */
  12. #include <stdarg.h>
  13. #include "sprintf_alloc.h"
  14. #include "libbb/libbb.h"
  15. void sprintf_alloc(char **str, const char *fmt, ...)
  16. {
  17. va_list ap;
  18. int n;
  19. unsigned int size = 0;
  20. *str = NULL;
  21. for (;;) {
  22. va_start(ap, fmt);
  23. n = vsnprintf(*str, size, fmt, ap);
  24. va_end(ap);
  25. if (n < 0) {
  26. fprintf(stderr, "%s: encountered an output or encoding"
  27. " error during vsnprintf.\n", __FUNCTION__);
  28. exit(EXIT_FAILURE);
  29. }
  30. if (n < size)
  31. break;
  32. /* Truncated, try again with more space. */
  33. size = n + 1;
  34. *str = xrealloc(*str, size);
  35. }
  36. }