[clang] [clang][analyzer] Fix a possible crash in CastSizeChecker (PR #134387)

Balázs Kéri via cfe-commits cfe-commits at lists.llvm.org
Fri Apr 4 07:35:12 PDT 2025


https://github.com/balazske created https://github.com/llvm/llvm-project/pull/134387

None

>From 8936d300045d96d8719ecee04c36b2b0cb5d96d6 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bal=C3=A1zs=20K=C3=A9ri?= <balazs.keri at ericsson.com>
Date: Fri, 4 Apr 2025 16:05:28 +0200
Subject: [PATCH] [clang][analyzer] Fix a possible crash in CastSizeChecker

---
 .../Checkers/CastSizeChecker.cpp              |  2 ++
 clang/test/Analysis/castsize.c                | 25 +++++++++++++++++++
 2 files changed, 27 insertions(+)
 create mode 100644 clang/test/Analysis/castsize.c

diff --git a/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp b/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
index 2cff97a591b8c..0b52c9bd8ac2a 100644
--- a/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/CastSizeChecker.cpp
@@ -62,6 +62,8 @@ static bool evenFlexibleArraySize(ASTContext &Ctx, CharUnits RegionSize,
   assert(Last && "empty structs should already be handled");
 
   const Type *ElemType = Last->getType()->getArrayElementTypeNoTypeQual();
+  if (!ElemType)
+    return false;
   CharUnits FlexSize;
   if (const ConstantArrayType *ArrayTy =
         Ctx.getAsConstantArrayType(Last->getType())) {
diff --git a/clang/test/Analysis/castsize.c b/clang/test/Analysis/castsize.c
new file mode 100644
index 0000000000000..139f79b8beb4b
--- /dev/null
+++ b/clang/test/Analysis/castsize.c
@@ -0,0 +1,25 @@
+// RUN: %clang_analyze_cc1 -verify %s \
+// RUN:   -analyzer-checker=core,unix.Malloc,alpha.core.CastSize
+
+void *malloc(unsigned long);
+
+struct s1 {
+  int a;
+  char x[];
+};
+
+struct s2 {
+  int a[100];
+  char x[];
+};
+
+union u {
+  struct s1 a;
+  struct s2 b;
+};
+
+static union u *test() {
+  union u *req;
+  req = malloc(5); // expected-warning{{Cast a region whose size is not a multiple of the destination type size}}
+  return req;
+}



More information about the cfe-commits mailing list