Using Visual Studio 2022 with its C++ implementation I noticed either sprintf() or snprintf() as well as the vsprintf(), vsnprintf() implementations do not behave like the answers here suggest it should -- that is, I can't query the length of the would-be buffer with them.
Instead, I need to call a shady _scprintf() or _vscprintf().
So while the answers above are probably right, I guess there's no "standard" or "portable" way to do this. The code should have some #ifdef to handle whether it's being compiled by GNU or MSBuild compilers.
That said, the equivalent to the currently best voted answer from Daniel Standage for Visual C++ would be:
int size = _scprintf("%d", 132);
char * a = malloc(size + 1);
sprintf(a, "%d", 132);
Then maybe a "portable" (may I dare call it "standard"?) approach would be:
#ifdef _MSC_VER
int size = _scprintf("%d", 132);
#else
int size = snprintf(NULL, 0, "%d", 132);
#endif
char * a = malloc(size + 1);
sprintf(a, "%d", 132);
Then we could hope for the best, that any other c compiler pre-processing this source would support the best voted answer. :)
str;-pasprintf, which will internallymallocthe needed amount of memory.