Skip to content

Commit

Permalink
add macro REALLOC_ARRAY
Browse files Browse the repository at this point in the history
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>
  • Loading branch information
René Scharfe authored and Junio C Hamano committed Sep 18, 2014
1 parent ce1d3a9 commit 3ac22f8
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Documentation/technical/api-allocation-growing.txt
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,6 @@ item[nr++] = value you like;
------------

You are responsible for updating the `nr` variable.

If you need to specify the number of elements to allocate explicitly
then use the macro `REALLOC_ARRAY(item, alloc)` instead of `ALLOC_GROW`.
2 changes: 2 additions & 0 deletions git-compat-util.h
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,8 @@ extern int odb_mkstemp(char *template, size_t limit, const char *pattern);
extern int odb_pack_keep(char *name, size_t namesz, const unsigned char *sha1);
extern char *xgetcwd(void);

#define REALLOC_ARRAY(x, alloc) (x) = xrealloc((x), (alloc) * sizeof(*(x)))

static inline size_t xsize_t(off_t len)
{
if (len > (size_t) len)
Expand Down

0 comments on commit 3ac22f8

Please sign in to comment.