A new wrinkle for printf()
Somewhere along the line the GNU C library and the BSD folks added variants of sprintf() that malloc() the resulting string. Very handy for avoiding an overflow situation and also makes for cleaner reading code.
`` int asprintf( char **ret, const char *format, …); int vasprintf( char **ret, const char *format, va_list ap);
Before:
`` char buf[32]; sprintf(buf, “s:%d m:%s”, code, msg); // stack overflow when msg is too long
… or …
``
char buf[1024];
snprintf( buf, sizeof(buf)-1, “s:%d m:%s”, code, msg); // fail oddly if we guessed wrong on the maximum buf size
After:
``
char *buf;
asprintf( &buf, “s:%d m:%s”, code, msg);
… free(buf);
Danger danger DANGER: This will not work on the tiny libc in OpenWRT and similar embedded systems. But at least you will get a link error during the build.
Now if only we had a scanf() that would do a realloc() on its pointers.