C sprintf function that uses malloc or the stack

1.5k Views Asked by At

I've heard there is a version of sprintf(), possibly a GNU/gcc extension which either allocates its own buffer which I must free() or perhaps works using the stack like alloca().

Either method is fine for me. Can anyone tell me what function I was thinking of?

1

There are 1 best solutions below

1
On BEST ANSWER

You probably mean asprintf ?

From the man page:


Description

The functions asprintf() and vasprintf() are analogues of sprintf() and vsprintf(), except that they allocate a string large enough to hold the output including the terminating null byte, and return a pointer to it via the first parameter. This pointer should be passed to free(3) to release the allocated storage when it is no longer needed.


Note that asprintf is a GNU extension, which is also found in various BSD implementations, but it's not in standard C or POSIX.