Blob Blame History Raw
From f2b8769e4a9aa99cd5e0aef41a0408c34de3cc8e Mon Sep 17 00:00:00 2001
From: "Dmitry V. Levin" <ldv@strace.io>
Date: Mon, 15 Mar 2021 08:00:00 +0000
Subject: [PATCH 145/149] xmalloc: introduce xasprintf

xasprintf is a trivial wrapper around vasprintf,
the primary purpose of adding it is to simplify tests.

* xmalloc.h (xasprintf): New function declaration.
* xmalloc.c: Include <stdarg.h> and <stdio.h>
(xasprintf): New function.
---
 xmalloc.c | 16 ++++++++++++++++
 xmalloc.h |  6 ++++++
 2 files changed, 22 insertions(+)

diff --git a/xmalloc.c b/xmalloc.c
index 8688f91..75019e9 100644
--- a/xmalloc.c
+++ b/xmalloc.c
@@ -10,6 +10,8 @@
 # include "config.h"
 #endif
 
+#include <stdarg.h>
+#include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
 
@@ -146,3 +148,17 @@ xstrndup(const char *str, size_t n)
 
 	return p;
 }
+
+char *
+xasprintf(const char *fmt, ...)
+{
+	va_list ap;
+	va_start(ap, fmt);
+
+	char *res;
+	if (vasprintf(&res, fmt, ap) < 0)
+		die_out_of_memory();
+
+	va_end(ap);
+	return res;
+}
diff --git a/xmalloc.h b/xmalloc.h
index 4bf1e2c..1305a1e 100644
--- a/xmalloc.h
+++ b/xmalloc.h
@@ -77,4 +77,10 @@ void *xgrowarray(void *ptr, size_t *nmemb, size_t memb_size);
 char *xstrdup(const char *str) ATTRIBUTE_MALLOC;
 char *xstrndup(const char *str, size_t n) ATTRIBUTE_MALLOC;
 
+/**
+ * Analogous to asprintf, die in case of an error.
+ */
+char *xasprintf(const char *fmt, ...)
+	ATTRIBUTE_FORMAT((printf, 1, 2)) ATTRIBUTE_MALLOC;
+
 #endif /* !STRACE_XMALLOC_H */
-- 
2.1.4