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.
comment by jim, 3 years ago
Oh look, there is a similar function for scanf(). You can do something like...
char *adj = 0;
sscanf(somestuff,"Some %as stuff", &adj);
... but only if you are using GNU libc. I got burned when I used this in a daemon and then moved it to OpenWRT where they uses a different libc.