view dmstring.c @ 96:6bf5220fa47e

Urgh .. use memset to silence some bogus GCC warnings about using potentially uninitialized values, while that will not actually be possible. In any case, it is annoying.
author Matti Hamalainen <ccr@tnsp.org>
date Tue, 02 Oct 2012 18:52:28 +0300
parents 32250b436bca
children 2726d91e3409
line wrap: on
line source

#include "dmlib.h"
#include <stdarg.h>

/* strdup with a NULL check
 */
char *dm_strdup(const char *s)
{
    char *res;
    if (s == NULL)
        return NULL;

    if ((res = dmMalloc(strlen(s) + 1)) == NULL)
        return NULL;

    strcpy(res, s);
    return res;
}


/* Simulate a sprintf() that allocates memory
 */
char *dm_strdup_vprintf(const char *fmt, va_list args)
{
    int size = 64;
    char *buf;

    if ((buf = dmMalloc(size)) == NULL)
        return NULL;

    while (1)
    {
        int n;
        va_list ap;
        va_copy(ap, args);
        n = vsnprintf(buf, size, fmt, ap);
        va_end(ap);

        if (n > -1 && n < size)
            return buf;
        if (n > -1)
            size = n + 1;
        else
            size *= 2;

        if ((buf = dmRealloc(buf, size)) == NULL)
            return NULL;
    }
}


char *dm_strdup_printf(const char *fmt, ...)
{
    char *res;
    va_list ap;

    va_start(ap, fmt);
    res = dm_strdup_vprintf(fmt, ap);
    va_end(ap);

    return res;
}