fork download
  1. #define _GNU_SOURCE
  2. #include <stdarg.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. #define DebugPointer(p) \
  8.   { \
  9.   printf("%8s %20s: %p\n", #p, "address", (void*)&(p)); \
  10.   printf("%8s %20s: %p\n", #p, "points to", (void*)(p)); \
  11.   }
  12.  
  13.  
  14. // memory-safe asprintf, implemented as a macro
  15. #define Sasprintf(write_to, ...) \
  16.   { \
  17.   char* tmp = (write_to); \
  18.   printf("==== before asprintf\n"); \
  19.   DebugPointer(tmp); \
  20.   DebugPointer(write_to); \
  21.   asprintf(&(write_to), __VA_ARGS__); \
  22.   printf("==== after asprintf\n"); \
  23.   DebugPointer(tmp); \
  24.   DebugPointer(write_to); \
  25.   free(tmp); \
  26.   }
  27.  
  28. int main() {
  29. char* s = NULL;
  30. int n = 0;
  31. Sasprintf(s, "%s", "aa\n");
  32. Sasprintf(s, "%s%s", s, "bb\n");
  33. Sasprintf(s, "%s%s", s, "cc\n");
  34. printf("string: %s\n", s);
  35. free(s);
  36. }
  37.  
Success #stdin #stdout 0s 9424KB
stdin
Standard input is empty
stdout
==== before asprintf
     tmp              address: 0x7fffcd0ce5f8
     tmp            points to: (nil)
       s              address: 0x7fffcd0ce5f0
       s            points to: (nil)
==== after  asprintf
     tmp              address: 0x7fffcd0ce5f8
     tmp            points to: (nil)
       s              address: 0x7fffcd0ce5f0
       s            points to: 0x55752df67090
==== before asprintf
     tmp              address: 0x7fffcd0ce5f8
     tmp            points to: 0x55752df67090
       s              address: 0x7fffcd0ce5f0
       s            points to: 0x55752df67090
==== after  asprintf
     tmp              address: 0x7fffcd0ce5f8
     tmp            points to: 0x55752df67090
       s              address: 0x7fffcd0ce5f0
       s            points to: 0x55752df670b0
==== before asprintf
     tmp              address: 0x7fffcd0ce5f8
     tmp            points to: 0x55752df670b0
       s              address: 0x7fffcd0ce5f0
       s            points to: 0x55752df670b0
==== after  asprintf
     tmp              address: 0x7fffcd0ce5f8
     tmp            points to: 0x55752df670b0
       s              address: 0x7fffcd0ce5f0
       s            points to: 0x55752df67090
string: aa
bb
cc