sprintf() with automatic memory allocation?

2019-01-03 17:13发布

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 retrieves the adress of an allocated 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 immediatelly 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 enought, then I could get it myself done.

Thanks a lot!

标签: c malloc printf
5条回答
beautiful°
2楼-- · 2019-01-03 17:20
  1. If possible, use snprintf -- it gives an easy way to measure the size of data that would be produced so you can allocate space.
  2. If you really can't do that, another possibility is printing to a temporary file with fprintf to get the size, allocate the memory, and then use sprintf. snprintf is definitely the preferred method though.
查看更多
Deceive 欺骗
3楼-- · 2019-01-03 17:30

If you can live with GNU/BSD extentions, the question is already answered. You can use asprintf() (and vasprintf() for building wrapper functions) and be done.

But snprintf() and vsnprintf() are mandated by POSIX, according to the manpage, and the latter can be used to build up your own simple version of asprintf() and vasprintf().

int
vasprintf(char **strp, const char *fmt, va_list ap)
{
    va_list ap1;
    size_t size;
    char *buffer;

    va_copy(ap1, ap);
    size = vsnprintf(NULL, 0, fmt, ap1) + 1;
    va_end(ap1);
    buffer = calloc(1, size);

    if (!buffer)
        return -1;

    *strp = buffer;

    return vsnprintf(buffer, size, fmt, ap);
}

int
asprintf(char **strp, const char *fmt, ...)
{
    int error;
    va_list ap;

    va_start(ap, fmt);
    error = vasprintf(strp, fmt, ap);
    va_end(ap);

    return error;
}

You can do some preprocessor magic and use your versions of functions only on systems that don't support them.

查看更多
Melony?
4楼-- · 2019-01-03 17:36

The GLib library provides a g_strdup_printf function that does exactly what you want, if linking against GLib is an option. From the documentation:

Similar to the standard C sprintf() function but safer, since it calculates the maximum space required and allocates memory to hold the result. The returned string should be freed with g_free() when no longer needed.

查看更多
姐就是有狂的资本
5楼-- · 2019-01-03 17:39

Here is the original answer from Stack Overflow. As others have mentioned, you need snprintf not sprintf. Make sure the second argument to snprintf is zero. That will prevent snprintf from writing to the NULL string that is the first argument.

The second argument is needed because it tells snprintf that enough space is not available to write to the output buffer. When enough space is not available snprintf returns the number of bytes it would have written, had enough space been available.

Reproducing the code from that link here ...

char* get_error_message(char const *msg) {
    size_t needed = snprintf(NULL, 0, "%s: %s (%d)", msg, strerror(errno), errno) + 1;
    char  *buffer = malloc(needed);
    sprintf(buffer, "%s: %s (%d)", msg, strerror(errno), errno);
    return buffer;
}
查看更多
何必那么认真
6楼-- · 2019-01-03 17:43

GNU and BSD have asprintf and vasprintf that are designed to do just that for you. It will figure out how to allocate the memory for you and will return null on any memory allocation error.

asprintf does the right thing with respect to allocating strings -- it first measures the size, then it tries to allocate with malloc. Failing that, it returns null. Unless you have your own memory allocation system that precludes the use of malloc, asprintf is the best tool for the job.

The code would look like:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{
    char*   ret;
    char*   a = "Hello";
    char*   b = "World";
    int     c = 123;

    ret = asprintf( "%s %d %s!", a, c, b );
    if (ret == NULL) {
        fprintf(stderr, "Error in asprintf\n");
        return 1;
    }

    printf( "ret = >%s<\n", ret );
    free( ret );

    return 0;
}
查看更多
登录 后发表回答