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

[PATCH] cocci: use ALLOC_ARRAY

From
René Scharfe <l.s.r@web.de>
Date
Feb 25, 2017, 10:30 UTC
Message-ID
<6652d950-7de3-3b6d-0a2d-414e0e4247f4@web.de>

Add a semantic patch for using ALLOC_ARRAY to allocate arrays and apply the transformation on the current source tree. The macro checks for multiplication overflow and infers the element size automatically; the result is shorter and safer code.

Signed-off-by: Rene Scharfe <l.s.r@web.de>
---
 contrib/coccinelle/array.cocci | 16 ++++++++++++++++
 worktree.c                     |  2 +-
 2 files changed, 17 insertions(+), 1 deletion(-)
diff --git a/contrib/coccinelle/array.cocci b/contrib/coccinelle/array.cocci
index 2d7f25d99f..4ba98b7eaf 100644
--- a/contrib/coccinelle/array.cocci
+++ b/contrib/coccinelle/array.cocci
@@ -24,3 +24,19 @@ expression n;
 @@
 - memcpy(dst, src, n * sizeof(T));
 + COPY_ARRAY(dst, src, n);
+
+@@
+type T;
+T *ptr;
+expression n;
+@@
+- ptr = xmalloc(n * sizeof(*ptr));
++ ALLOC_ARRAY(ptr, n);
+
+@@
+type T;
+T *ptr;
+expression n;
+@@
+- ptr = xmalloc(n * sizeof(T));
++ ALLOC_ARRAY(ptr, n);
diff --git a/worktree.c b/worktree.c
index d633761575..d7b911aac7 100644
--- a/worktree.c
+++ b/worktree.c
@@ -175,7 +175,7 @@ struct worktree **get_worktrees(unsigned flags)
 	struct dirent *d;
 	int counter = 0, alloc = 2;
 
-	list = xmalloc(alloc * sizeof(struct worktree *));
+	ALLOC_ARRAY(list, alloc);
 
 	list[counter++] = get_main_worktree();
 
-- 
2.12.0
Message 1 of 1 in “cocci: use ALLOC_ARRAY”
  1. cocci: use ALLOC_ARRAYRené Scharfe, Feb 25, 2017

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.