Reimplement xAsnprintf and xSnprintf as type-safe functions

This commit is contained in:
Benny Baumann 2020-09-18 20:38:25 +02:00
parent 241e4b3dbf
commit 8b55113ea8
2 changed files with 32 additions and 4 deletions

View File

@ -5,6 +5,8 @@
#ifndef _GNU_SOURCE #ifndef _GNU_SOURCE
#define _GNU_SOURCE #define _GNU_SOURCE
#endif #endif
#include <stdarg.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -39,6 +41,32 @@ void* xRealloc(void* ptr, size_t size) {
return data; 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* xStrdup_(const char* str) {
char* data = strdup(str); char* data = strdup(str);
if (!data) { if (!data) {

View File

@ -19,11 +19,11 @@ void* xCalloc(size_t nmemb, size_t size);
void* xRealloc(void* ptr, 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) ATTR_FORMAT(printf, 3, 4)
int xSnprintf(char *buf, int len, const char* fmt, ...);
#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)
#undef xStrdup #undef xStrdup
#undef xStrdup_ #undef xStrdup_