git/list[1] front-page[2] threads[3] people[4] search[5] about
 

[PATCH] evaluate the second argument of ALLOC_GROW only once

From
René Scharfe <l.s.r@web.de>
Date
May 15, 2026, 18:16 UTC
Message-ID
<323f5677-301b-4d7a-b552-6606597c2b1f@web.de>

Allow the new element count passed to ALLOC_GROW to be a complex expression with side-effects by evaluating it only once, as a parameter to a new helper function.

Suggested-by: Junio C Hamano <gitster@pobox.com>
Signed-off-by: René Scharfe <l.s.r@web.de>
---
 git-compat-util.h | 20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
diff --git a/git-compat-util.h b/git-compat-util.h
index ae1bdc90a4..2bc1f43f48 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -812,6 +812,16 @@ static inline void move_array(void *dst, const void *src, size_t n, size_t size)
 
 #define alloc_nr(x) (((x)+16)*3/2)
 
+static inline bool st_alloc_nr(size_t nr, size_t alloc, size_t *outp)
+{
+	if (nr > alloc) {
+		size_t out = alloc_nr(alloc);
+		*outp = out < nr ? nr : out;
+		return true;
+	}
+	return false;
+}
+
 /**
  * Dynamically growing an array using realloc() is error prone and boring.
  *
@@ -857,12 +867,10 @@ static inline void move_array(void *dst, const void *src, size_t n, size_t size)
  */
 #define ALLOC_GROW(x, nr, alloc) \
 	do { \
-		if ((nr) > alloc) { \
-			if (alloc_nr(alloc) < (nr)) \
-				alloc = (nr); \
-			else \
-				alloc = alloc_nr(alloc); \
-			REALLOC_ARRAY(x, alloc); \
+		size_t alloc_grow_new_alloc_; \
+		if (st_alloc_nr((nr), (alloc), &alloc_grow_new_alloc_)) { \
+			alloc = alloc_grow_new_alloc_; \
+			REALLOC_ARRAY(x, alloc_grow_new_alloc_); \
 		} \
 	} while (0)
 
-- 
2.54.0
Next: Jeff King
Message 1 of 8 in “evaluate the second argument of ALLOC_GROW only once”
  1. evaluate the second argument of ALLOC_GROW only onceRené Scharfe, May 15, 2026
  2. Jeff KingMay 15, 2026
  3. Jeff KingMay 15, 2026
  4. René ScharfeMay 15, 2026
  5. Jeff KingMay 16, 2026
  6. René ScharfeMay 16, 2026
  7. Johannes SixtMay 16, 2026
  8. Jeff KingMay 19, 2026

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.