Skip to contentSkip to conversation

checkpatch: Add --strict preference for p = kmalloc(sizeof(*p)...

PATCH New Joe Perches 1 participant 1 message May 18, 2013 Checkpatch

lore
Share & tools
lore

Joe Perches

author maintainer
#0 lore raw

PATCH 1/1 checkpatch: Add --strict preference for p = kmalloc(sizeof(*p)...

Add another test for memory allocation style to follow Documentation/CodingStyle:

Chapter 14: Allocating memory

The preferred form for passing a size of a struct is the following:

	p = kmalloc(sizeof(*p), ...);
---
 scripts/checkpatch.pl | 8 ++++++++
 1 file changed, 8 insertions(+)
scripts/checkpatch.pl +8 -0
index b954de5..1803907 100755
@@ -3495,6 +3495,14 @@ sub process {
 			     "unnecessary cast may hide bugs, see http://c-faq.com/malloc/mallocnocast.html\n" . $herecurr);
 		}
 
+# alloc style
+# p = alloc(sizeof(struct foo), ...) should be p = alloc(sizeof(*p), ...)
+		if ($^V && $^V ge 5.10.0 &&
+		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*([kv][mz]alloc(?:_node)?)\s*\(\s*(sizeof\s*\(\s*struct\s+$Lval\s*\))/) {
+			CHK("ALLOC_SIZEOF_STRUCT",
+			    "Prefer $3(sizeof(*$1)...) over $3($4...)\n" . $herecurr);
+		}
+
 # check for krealloc arg reuse
 		if ($^V && $^V ge 5.10.0 &&
 		    $line =~ /\b($Lval)\s*\=\s*(?:$balanced_parens)?\s*krealloc\s*\(\s*\1\s*,/) {