asprintf.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /* Like sprintf but provides a pointer to malloc'd storage, which must
  2. be freed by the caller.
  3. Copyright (C) 1997, 2003, 2013 Free Software Foundation, Inc.
  4. Contributed by Cygnus Solutions.
  5. This file is part of the libiberty library.
  6. Libiberty is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU Library General Public
  8. License as published by the Free Software Foundation; either
  9. version 2 of the License, or (at your option) any later version.
  10. Libiberty is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. Library General Public License for more details.
  14. You should have received a copy of the GNU Library General Public
  15. License along with libiberty; see the file COPYING.LIB. If
  16. not, write to the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
  17. Boston, MA 02110-1301, USA. */
  18. #ifdef HAVE_CONFIG_H
  19. #include "config.h"
  20. #endif
  21. #include "ansidecl.h"
  22. #include "libiberty.h"
  23. #include <stdarg.h>
  24. /*
  25. @deftypefn Extension int asprintf (char **@var{resptr}, const char *@var{format}, ...)
  26. Like @code{sprintf}, but instead of passing a pointer to a buffer, you
  27. pass a pointer to a pointer. This function will compute the size of
  28. the buffer needed, allocate memory with @code{malloc}, and store a
  29. pointer to the allocated memory in @code{*@var{resptr}}. The value
  30. returned is the same as @code{sprintf} would return. If memory could
  31. not be allocated, minus one is returned and @code{NULL} is stored in
  32. @code{*@var{resptr}}.
  33. @end deftypefn
  34. */
  35. int
  36. asprintf (char **buf, const char *fmt, ...)
  37. {
  38. int status;
  39. va_list ap;
  40. va_start (ap, fmt);
  41. status = vasprintf (buf, fmt, ap);
  42. va_end (ap);
  43. return status;
  44. }