I'm searching for a sprintf()-like implementation of a function that automatically allocates required memory. So I want to say
char* my_str = dynamic_sprintf( "Hello %s, this is a %.*s nice %05d string", a, b, c, d );
and my_str retrieves the adress of an allocated memory that holds the result of this sprintf().
In another forum, I read that this can be solved like this:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
char* ret;
char* a = "Hello";
char* b = "World";
int c = 123;
int numbytes;
numbytes = sprintf( (char*)NULL, "%s %d %s!", a, c, b );
printf( "numbytes = %d", numbytes );
ret = (char*)malloc( ( numbytes + 1 ) * sizeof( char ) );
sprintf( ret, "%s %d %s!", a, c, b );
printf( "ret = >%s<\n", ret );
free( ret );
return 0;
}
But this immediatelly results in a segfault when the sprintf() with the NULL-pointer is invoked.
So any idea, solution or tips? A small implementation of a sprintf()-like parser that is placed in the public domain would already be enought, then I could get it myself done.
Thanks a lot!
snprintf
-- it gives an easy way to measure the size of data that would be produced so you can allocate space.fprintf
to get the size, allocate the memory, and then use sprintf.snprintf
is definitely the preferred method though.If you can live with GNU/BSD extentions, the question is already answered. You can use
asprintf()
(andvasprintf()
for building wrapper functions) and be done.But
snprintf()
andvsnprintf()
are mandated by POSIX, according to the manpage, and the latter can be used to build up your own simple version ofasprintf()
andvasprintf()
.You can do some preprocessor magic and use your versions of functions only on systems that don't support them.
The GLib library provides a
g_strdup_printf
function that does exactly what you want, if linking against GLib is an option. From the documentation:Here is the original answer from Stack Overflow. As others have mentioned, you need
snprintf
notsprintf
. Make sure the second argument tosnprintf
iszero
. That will preventsnprintf
from writing to theNULL
string that is the first argument.The second argument is needed because it tells
snprintf
that enough space is not available to write to the output buffer. When enough space is not availablesnprintf
returns the number of bytes it would have written, had enough space been available.Reproducing the code from that link here ...
GNU and BSD have asprintf and vasprintf that are designed to do just that for you. It will figure out how to allocate the memory for you and will return null on any memory allocation error.
asprintf does the right thing with respect to allocating strings -- it first measures the size, then it tries to allocate with malloc. Failing that, it returns null. Unless you have your own memory allocation system that precludes the use of malloc, asprintf is the best tool for the job.
The code would look like: