Node:asprintf, Next:, Previous:fprintf, Up:String output and input


The asprintf (mnemonic: "allocating string print formatted") command is identical to printf, except that its first parameter is a string to which to send output. It terminates the string with a null character. It returns the number of characters stored in the string, not including the terminating null.

The asprintf function is nearly identical to the simpler sprintf, but is much safer, because it dynamically allocates the string to which it sends output, so that the string will never overflow. The first parameter is a pointer to a string variable, that is, it is of type char **. The return value is the number of characters allocated to the buffer, or a negative value if an error occurred.

The following code example prints the string Being 4 is cool, but being free is best of all. to the string variable my_string, then prints the string on the screen. Notice that my_string is not initially allocated any space at all; asprintf allocates the space itself. (See puts, for more information on the puts function.)

#include <stdio.h>

int main()
  char *my_string;

  asprintf (&my_string, "Being %d is cool, but being free is best of all.", 4);
  puts (my_string);

  return 0;