Skip to content

Commit 3ac22f8

Browse files
rscharfegitster
authored andcommitted
add macro REALLOC_ARRAY
The macro ALLOC_GROW manages several aspects of dynamic memory allocations for arrays: It performs overprovisioning in order to avoid reallocations in future calls, updates the allocation size variable, multiplies the item size and thus allows users to simply specify the item count, performs the reallocation and updates the array pointer. Sometimes this is too much. Add the macro REALLOC_ARRAY, which only takes care of the latter three points and allows users to specfiy the number of items the array can store. It can increase and also decrease the size. Using the macro avoid duplicating the variable name and takes care of the item sizes automatically. Signed-off-by: Rene Scharfe <l.s.r@web.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
1 parent ce1d3a9 commit 3ac22f8

File tree

2 files changed

+5
-0
lines changed

2 files changed

+5
-0
lines changed

Documentation/technical/api-allocation-growing.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,6 @@ item[nr++] = value you like;
3434
------------
3535

3636
You are responsible for updating the `nr` variable.
37+
38+
If you need to specify the number of elements to allocate explicitly
39+
then use the macro `REALLOC_ARRAY(item, alloc)` instead of `ALLOC_GROW`.

git-compat-util.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -626,6 +626,8 @@ extern int odb_mkstemp(char *template, size_t limit, const char *pattern);
626626
extern int odb_pack_keep(char *name, size_t namesz, const unsigned char *sha1);
627627
extern char *xgetcwd(void);
628628

629+
#define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), (alloc) * sizeof(*(x)))
630+
629631
static inline size_t xsize_t(off_t len)
630632
{
631633
if (len > (size_t) len)

0 commit comments

Comments
 (0)