1
0
Fork 0
mirror of https://github.com/git/git.git synced 2024-11-15 05:33:04 +01:00
git/Documentation/technical/api-allocation-growing.txt
René Scharfe 3ac22f82ed 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>
2014-09-18 09:13:38 -07:00

39 lines
1.1 KiB
Text

allocation growing API
======================
Dynamically growing an array using realloc() is error prone and boring.
Define your array with:
* a pointer (`item`) that points at the array, initialized to `NULL`
(although please name the variable based on its contents, not on its
type);
* an integer variable (`alloc`) that keeps track of how big the current
allocation is, initialized to `0`;
* another integer variable (`nr`) to keep track of how many elements the
array currently has, initialized to `0`.
Then before adding `n`th element to the item, call `ALLOC_GROW(item, n,
alloc)`. This ensures that the array can hold at least `n` elements by
calling `realloc(3)` and adjusting `alloc` variable.
------------
sometype *item;
size_t nr;
size_t alloc
for (i = 0; i < nr; i++)
if (we like item[i] already)
return;
/* we did not like any existing one, so add one */
ALLOC_GROW(item, nr + 1, alloc);
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`.