common/string-helpers.c: add strdup_printf()

This commit is contained in:
Johan Malm 2023-06-25 09:00:41 +01:00 committed by Johan Malm
parent 41de529fff
commit f4f35a9dff
4 changed files with 47 additions and 23 deletions

View file

@ -1,7 +1,9 @@
// SPDX-License-Identifier: GPL-2.0-only
#include <ctype.h>
#include <stdarg.h>
#include <stdio.h>
#include <string.h>
#include "common/mem.h"
#include "common/string-helpers.h"
static void
@ -37,3 +39,32 @@ string_truncate_at_pattern(char *buf, const char *pattern)
}
*p = '\0';
}
char *
strdup_printf(const char *fmt, ...)
{
size_t size = 0;
char *p = NULL;
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0) {
return NULL;
}
size = (size_t)n + 1;
p = xzalloc(size);
va_start(ap, fmt);
n = vsnprintf(p, size, fmt, ap);
va_end(ap);
if (n < 0) {
free(p);
return NULL;
}
return p;
}