开发者

sprintf() with automatic memory allocation?

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!


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


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:

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

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

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

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

    return 0;
}


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;
    int len;
    char *buffer;
    int res;

    va_copy(ap1, ap);
    len = vsnprintf(NULL, 0, fmt, ap1);

    if (len < 0)
        return len;

    va_end(ap1);
    buffer = malloc(len + 1);

    if (!buffer)
        return -1;

    res = vsnprintf(buffer, len + 1, fmt, ap);

    if (res < 0)
        free(buffer);
    else
        *strp = buffer;

    return res;
}

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.


  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.


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.


POSIX.1 (aka IEEE 1003.1-2008) provides open_memstream:

char *ptr;
size_t size;
FILE *f = open_memstream(&ptr, &size);
fprintf(f, "lots of stuff here\n");
fclose(f);
write(1, ptr, size); /* for example */
free(ptr);

open_memstream(3) is available on at least Linux and macOS and has been for some years. The converse of open_memstream(3) is fmemopen(3) which makes the contents of a buffer available for reading.

If you just want a single sprintf(3) then the widely-implemented but non-standard asprintf(3) might be what you want.


/*  casprintf print to allocated or reallocated string

char *aux = NULL;
casprintf(&aux,"first line\n");
casprintf(&aux,"seconde line\n");
printf(aux);
free(aux);
*/
int vcasprintf(char **strp,const char *fmt,va_list ap)
{
  int ret;
  char *strp1;
  char *result;
  if (*strp==NULL)
     return vasprintf(strp,fmt,ap);

  ret=vasprintf(&strp1,fmt,ap); // ret = strlen(strp1) or -1
  if (ret == -1 ) return ret;
  if (ret==0) {free(strp1);return strlen(*strp);}

  size_t len = strlen(*strp);
  *strp=realloc(*strp,len + ret +1);
  memcpy((*strp)+len,strp1,ret+1);
  free(strp1);
  return(len+ret);
}

int casprintf(char **strp, const char *fmt, ...)
{
 int ret;
 va_list ap;
 va_start(ap,fmt);
 ret =vcasprintf(strp,fmt,ap);
 va_end(ap);
 return(ret);
}


My version (v3) of https://stackoverflow.com/a/10388547/666907 – a bit more universal [note I'm a C++ noob, use at your own risk :P]:

#include <cstdarg>

char* myFormat(const char* const format...) {
  // `vsnprintf()` changes `va_list`'s state, so using it after that is UB.
  // We need the args twice, so it is safer to just get two copies.
  va_list args1;
  va_list args2;
  va_start(args1, format);
  va_start(args2, format);

  size_t needed = 1 + vsnprintf(nullptr, 0, format, args1);

  // they say to cast in C++, so I cast…
  // https://stackoverflow.com/a/5099675/666907
  char* buffer = (char*) malloc(needed);

  vsnprintf(buffer, needed, format, args2);

  va_end(args1);
  va_end(args2);

  return buffer;
}

char* formatted = myFormat("Foo %s: %d", "bar", 456);
Serial.println(formatted); // Foo bar: 456

free(formatted); // remember to free or u will have a memory leak!
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜