summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBenny Baumann <BenBE@geshi.org>2020-09-18 20:38:25 +0200
committerBenny Baumann <BenBE@geshi.org>2020-09-29 17:41:31 +0200
commit8b55113ea8924d6e4ace14a3d54c9d9aca23eaa7 (patch)
treea677af6cf6b361d0a28c9bbc6e3a4baf5967a4a1
parent241e4b3dbf8ebee4a12a337dec725b3547c242e9 (diff)
Reimplement xAsnprintf and xSnprintf as type-safe functions
-rw-r--r--XAlloc.c28
-rw-r--r--XAlloc.h8
2 files changed, 32 insertions, 4 deletions
diff --git a/XAlloc.c b/XAlloc.c
index 294eb36a..c43eca76 100644
--- a/XAlloc.c
+++ b/XAlloc.c
@@ -5,6 +5,8 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
+
+#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
@@ -39,6 +41,32 @@ void* xRealloc(void* ptr, size_t size) {
return data;
}
+int xAsprintf(char** strp, const char* fmt, ...) {
+ va_list vl;
+ va_start(vl, fmt);
+ int _r = vasprintf(strp, fmt, vl);
+ va_end(vl);
+
+ if (_r < 0) {
+ fail();
+ }
+
+ return _r;
+}
+
+int xSnprintf(char* buf, int len, const char* fmt, ...) {
+ va_list vl;
+ va_start(vl, fmt);
+ int _n=vsnprintf(buf, len, fmt, vl);
+ va_end(vl);
+
+ if (!(_n > -1 && _n < len)) {
+ fail();
+ }
+
+ return _n;
+}
+
char* xStrdup_(const char* str) {
char* data = strdup(str);
if (!data) {
diff --git a/XAlloc.h b/XAlloc.h
index cebe095c..70dfc59f 100644
--- a/XAlloc.h
+++ b/XAlloc.h
@@ -19,11 +19,11 @@ void* xCalloc(size_t nmemb, size_t size);
void* xRealloc(void* ptr, size_t size);
-#undef xAsprintf
+ATTR_FORMAT(printf, 2, 3)
+int xAsprintf(char **strp, const char* fmt, ...);
-#define xAsprintf(strp, fmt, ...) do { int _r=asprintf(strp, fmt, __VA_ARGS__); if (_r < 0) { fail(); } } while(0)
-
-#define xSnprintf(fmt, len, ...) do { int _l=len; int _n=snprintf(fmt, _l, __VA_ARGS__); if (!(_n > -1 && _n < _l)) { curs_set(1); endwin(); err(1, NULL); } } while(0)
+ATTR_FORMAT(printf, 3, 4)
+int xSnprintf(char *buf, int len, const char* fmt, ...);
#undef xStrdup
#undef xStrdup_