galloca: Add new API g_alloca0 and g_newa0

Added `g_alloca0()` which wraps `g_alloca()` and initializes
allocated memory to zeroes.

Added `g_newa0()` which wraps `g_alloca0()` in a typesafe manner.

Refreshed and tweaked by Nishal Kulkarni.
This commit is contained in:
Marc-André Lureau 2021-11-25 13:38:11 +05:30 committed by Philip Withnall
parent f8bfd73e30
commit b4631c44ad
2 changed files with 33 additions and 0 deletions

View File

@ -1389,7 +1389,9 @@ g_mem_gc_friendly
<SUBSECTION>
g_alloca
g_alloca0
g_newa
g_newa0
<SUBSECTION>
g_memmove

View File

@ -30,6 +30,7 @@
#endif
#include <glib/gtypes.h>
#include <string.h>
#if defined(__BIONIC__) && defined (GLIB_HAVE_ALLOCA_H)
# include <alloca.h>
@ -94,6 +95,22 @@ G_END_DECLS
* Returns: space for @size bytes, allocated on the stack
*/
#define g_alloca(size) alloca (size)
/**
* g_alloca0:
* @size: number of bytes to allocate.
*
* Wraps g_alloca() and initializes allocated memory to zeroes.
* If @size is `0` it returns %NULL.
*
* Note that the @size argument will be evaluated multiple times.
*
* Returns: (nullable) (transfer full): space for @size bytes, allocated on the stack
*
* Since: 2.72
*/
#define g_alloca0(size) ((size) == 0 ? NULL : memset (g_alloca (size), 0, (size)))
/**
* g_newa:
* @struct_type: Type of memory chunks to be allocated
@ -111,4 +128,18 @@ G_END_DECLS
*/
#define g_newa(struct_type, n_structs) ((struct_type*) g_alloca (sizeof (struct_type) * (gsize) (n_structs)))
/**
* g_newa0:
* @struct_type: the type of the elements to allocate.
* @n_structs: the number of elements to allocate.
*
* Wraps g_alloca0() in a more typesafe manner.
*
* Returns: (nullable) (transfer full): Pointer to stack space for @n_structs
* chunks of type @struct_type
*
* Since: 2.72
*/
#define g_newa0(struct_type, n_structs) ((struct_type*) g_alloca0 (sizeof (struct_type) * (gsize) (n_structs)))
#endif /* __G_ALLOCA_H__ */