shared: return NULL from nm_malloc_maybe_a() when asking for zero bytes

The documentation of g_alloca()/alloca() isn't clear about what
happens when asking for zero bytes. Make it clear, by always returning
NULL.

Also, add a static assertion that @alloca_maxlen is a well-defined
positive integer.
This commit is contained in:
Thomas Haller 2020-10-02 11:34:31 +02:00
parent 456d26d816
commit 978145f8ba
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728

View file

@ -1491,23 +1491,24 @@ nm_memdup(gconstpointer data, gsize size)
return p;
}
#define nm_malloc_maybe_a(alloca_maxlen, bytes, to_free) \
({ \
const gsize _bytes = (bytes); \
typeof(to_free) _to_free = (to_free); \
typeof(*_to_free) _ptr; \
\
G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500); \
nm_assert(_to_free && !*_to_free); \
\
if (_bytes <= (alloca_maxlen)) { \
_ptr = g_alloca(_bytes); \
} else { \
_ptr = g_malloc(_bytes); \
*_to_free = _ptr; \
}; \
\
_ptr; \
#define nm_malloc_maybe_a(alloca_maxlen, bytes, to_free) \
({ \
const gsize _bytes = (bytes); \
typeof(to_free) _to_free = (to_free); \
typeof(*_to_free) _ptr; \
\
G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500u); \
G_STATIC_ASSERT_EXPR((alloca_maxlen) > 0u); \
nm_assert(_to_free && !*_to_free); \
\
if (G_LIKELY(_bytes <= (alloca_maxlen))) { \
_ptr = _bytes > 0u ? g_alloca(_bytes) : NULL; \
} else { \
_ptr = g_malloc(_bytes); \
*_to_free = _ptr; \
}; \
\
_ptr; \
})
#define nm_malloc0_maybe_a(alloca_maxlen, bytes, to_free) \
@ -1516,12 +1517,16 @@ nm_memdup(gconstpointer data, gsize size)
typeof(to_free) _to_free = (to_free); \
typeof(*_to_free) _ptr; \
\
G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500); \
G_STATIC_ASSERT_EXPR((alloca_maxlen) <= 500u); \
G_STATIC_ASSERT_EXPR((alloca_maxlen) > 0u); \
nm_assert(_to_free && !*_to_free); \
\
if (_bytes <= (alloca_maxlen)) { \
_ptr = g_alloca(_bytes); \
memset(_ptr, 0, _bytes); \
if (G_LIKELY(_bytes <= (alloca_maxlen))) { \
if (_bytes > 0u) { \
_ptr = g_alloca(_bytes); \
memset(_ptr, 0, _bytes); \
} else \
_ptr = NULL; \
} else { \
_ptr = g_malloc0(_bytes); \
*_to_free = _ptr; \