xmalloc.c: introduce xgrowarray helper function

In order to simplify dynamic array management code.

* xmalloc.h (xgrowarray): New declaration.
* xmalloc.c (xgrowarray): New function.
This commit is contained in:
Eugene Syromiatnikov 2017-08-08 16:36:40 +02:00 committed by Dmitry V. Levin
parent d55a53c758
commit 057a8f2274
2 changed files with 39 additions and 0 deletions

View File

@ -89,6 +89,28 @@ xreallocarray(void *ptr, size_t nmemb, size_t size)
return p;
}
void *
xgrowarray(void *const ptr, size_t *const nmemb, const size_t memb_size)
{
/* this is the same value as glibc DEFAULT_MXFAST */
enum { DEFAULT_ALLOC_SIZE = 64 * SIZEOF_LONG / 4 };
size_t grow_memb;
if (ptr == NULL)
grow_memb = *nmemb ? 0 :
(DEFAULT_ALLOC_SIZE + memb_size - 1) / memb_size;
else
grow_memb = (*nmemb >> 1) + 1;
if ((*nmemb + grow_memb) < *nmemb)
die_out_of_memory();
*nmemb += grow_memb;
return xreallocarray(ptr, *nmemb, memb_size);
}
char *
xstrdup(const char *str)
{

View File

@ -42,6 +42,23 @@ void *xmalloc(size_t size) ATTRIBUTE_MALLOC ATTRIBUTE_ALLOC_SIZE((1));
void *xreallocarray(void *ptr, size_t nmemb, size_t size)
ATTRIBUTE_ALLOC_SIZE((2, 3));
/**
* Utility function for the simplification of managing various dynamic arrays.
* Knows better how to resize arrays. Dies if there's no enough memory.
*
* @param[in] ptr Pointer to the array to be resized. If ptr is NULL,
* new array is allocated.
* @param[in, out] nmemb Pointer to the current member count. If ptr is
* NULL, it specifies number of members in the newly
* created array. If ptr is NULL and nmemb is 0,
* number of members in the new array is decided by
* the function. Member count is updated by the
* function to the new value.
* @param[in] memb_size Size of array member in bytes.
* @return Pointer to the (re)allocated array.
*/
void *xgrowarray(void *ptr, size_t *nmemb, size_t memb_size);
/*
* Note that the following two functions return NULL when NULL is specified
* and not when allocation is failed, since, as the "x" prefix implies,