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 receives the address of an allocated block of 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 immediately 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 enough, then I could get it myself done.
Thanks a lot!
 
     
     
     
     
     
     
     
     
     
     
     
    