One of the problem that has always existed in c programming is to create a big enough buffer in order to store a string. This can create a chicken / egg problem when trying to use sprintf or snprintf where you don't know how big the buffer actually needs to be to store the string.
There is another function in Linux which will allocate a buffer which is called asprintf (allocate string printf). this will make sure that the buffer is always going to be big enough to store the data and does not suffer from the same
problems when using sprintf or snprintf.
The cost of using this is of course is performance related since it needs to allocate memory and you also need to free it later. This type of allocation can be expensive if called a large number of times. There is also of course the problem of remembering to free the allocated memory later or it will create a memory leak.
To use this function you also need to define _GNU_SOURCE on the gcc command line (of in the program with a define before the includes)
Here is an example of using asprintf.
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
char *tmp = 0;
if (asprintf(&tmp, "%s %d", "Magic Number", 1234) < 0) {
perror("asprintf");
exit(EXIT_FAILURE);
}
printf("%s\n", tmp);
free(tmp);
return 0;
}
Did You find this page useful?
Yes
No