threads / patch / 45224

patchcocci: use ALLOC_ARRAY

Subject: [PATCH] cocci: use ALLOC_ARRAY

## tl;dr

One message between Feb 25, 2017 and Feb 25, 2017. Diffs are folded; open one to read it.

replies: 0people: 1as markdown or json

René Scharfe· Feb 25, 2017, 10:30 UTC · lore

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(-)
Show changes to 2 files +17 −1

contrib/coccinelle/array.cocci, worktree.c

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

← back to recent threads