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;
}




Last Modified: 12 December 2016

Releated Posts


2013-02-16 - C - Some simple examples of using strcat
2012-11-03 - C - How to override malloc / free
2012-09-22 - Linux Programming - Using inotify for detecting file modifications
2012-08-09 - C++ - Check an IP Address is in a IP Mask
2012-04-05 - Using gdb to debug a core file
2012-03-15 - C - Is the stdin a tty
2012-03-13 - C - Converting from char / string to int using atoi
2012-03-08 - C - UDP Socket example
2012-02-20 - C - Get home dir location in linux
2012-02-17 - C - IP address validation
2012-02-15 - C - Get current ip address of an interface
2012-02-10 - Using asprintf instead of sprintf or snprintf
2012-01-31 - C - Example of how to overwrite argv
2012-01-30 - C - The string reverse
2012-01-27 - C - Palindrome
2012-01-26 - C - Example of using popen
2011-12-28 - C - gethostbyname example
2011-12-11 - C - Linux get mac address from interface