fork download
  1. /************************************ asprintf.h ****************************************/
  2.  
  3. /* Sources:
  4.   https://stackoverflow.com/questions/40159892/using-asprintf-on-
  5.   https://stackoverflow.com/questions/4785381/replacement-for-ms-vscprintf-on-macos-linux
  6. */
  7.  
  8. #include <stdio.h> /* needed for vsnprintf */
  9. #include <stdlib.h> /* needed for malloc-free */
  10. #include <stdarg.h> /* needed for va_list */
  11.  
  12. #ifndef _vscprintf
  13. /* For some reason, MSVC fails to honour this #ifndef. */
  14. /* Hence the function was renamed to _vscprintf_so(). */
  15. int _vscprintf_so(const char * format, va_list pargs) {
  16. int retval;
  17. va_list argcopy;
  18. va_copy(argcopy, pargs);
  19. retval = vsnprintf(NULL, 0, format, argcopy);
  20. va_end(argcopy);
  21. return retval;
  22. }
  23. #endif // _vscprintf
  24.  
  25. #ifndef vasprintf
  26. int vasprintf(char **strp, const char *fmt, va_list ap) {
  27. int len = _vscprintf_so(fmt, ap);
  28. if (len == -1) return -1;
  29. char *str = malloc((size_t) len + 1);
  30. if (!str) return -1;
  31. int r = vsnprintf(str, len + 1, fmt, ap); /* "secure" version of vsprintf */
  32. if (r == -1) return free(str), -1;
  33. *strp = str;
  34. return r;
  35. }
  36. #endif // vasprintf
  37.  
  38. #ifndef asprintf
  39. int asprintf(char *strp[], const char *fmt, ...) {
  40. va_list ap;
  41. va_start(ap, fmt);
  42. int r = vasprintf(strp, fmt, ap);
  43. va_end(ap);
  44. return r;
  45. }
  46. #endif // asprintf
  47.  
  48. /************************************** main.c ******************************************/
  49.  
  50. #include <stdio.h> /* needed for puts */
  51. #include <stdlib.h> /* needed for free */
  52. // #include "asprintf.h" /* Commented out for online compilers. Uncomment in desktop compiler. */
  53.  
  54. int main(void) {
  55. char *b;
  56. asprintf(&b, "Mama %s is equal %d.", "John", 58);
  57. puts(b); /* Expected: "Mama John is equal 58." */
  58. free(b); /* Important! */
  59. return 0;
  60. }
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
Mama John is equal 58.