Add assert and __attribute__((nonnull)) on xStrdup

__attribute__((nonnull)) will help catching "calling with NULL" mistake on
compile time.

I also convert xStrdup into a macro, that will do assert() inline when the
code is *not* built with -DNDEBUG . For release builds (with -DNDEBUG),
preprocessor trick will ensure that generated code remains the same.
This commit is contained in:
Explorer09 2016-06-02 20:38:24 +08:00
parent e288f690af
commit 3297616efa
2 changed files with 27 additions and 2 deletions

View File

@ -5,6 +5,7 @@
#ifndef _GNU_SOURCE #ifndef _GNU_SOURCE
#define _GNU_SOURCE #define _GNU_SOURCE
#endif #endif
#include <assert.h>
#include <err.h> #include <err.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -43,7 +44,19 @@ void* xRealloc(void* ptr, size_t size) {
return data; return data;
} }
char* xStrdup(const char* str) { #undef xStrdup
#undef xStrdup_
#ifdef NDEBUG
# define xStrdup_ xStrdup
#else
# define xStrdup(str_) (assert(str_), xStrdup_(str_))
#endif
#if ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))
char* xStrdup_(const char* str) __attribute__((nonnull));
#endif // GNU C 3.3 or later
char* xStrdup_(const char* str) {
char* data = strdup(str); char* data = strdup(str);
if (!data) { if (!data) {
fail(); fail();

View File

@ -15,6 +15,18 @@ void* xCalloc(size_t nmemb, size_t size);
void* xRealloc(void* ptr, size_t size); void* xRealloc(void* ptr, size_t size);
char* xStrdup(const char* str); #undef xStrdup
#undef xStrdup_
#ifdef NDEBUG
# define xStrdup_ xStrdup
#else
# define xStrdup(str_) (assert(str_), xStrdup_(str_))
#endif
#if ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3))
char* xStrdup_(const char* str) __attribute__((nonnull));
#endif // GNU C 3.3 or later
char* xStrdup_(const char* str);
#endif #endif