[compiler-rt] 7450a00 - [msan] Add test for deferencing zero-sized malloc/calloc (#155934)

via llvm-commits llvm-commits at lists.llvm.org
Thu Aug 28 15:48:35 PDT 2025


Author: Thurston Dang
Date: 2025-08-28T15:48:31-07:00
New Revision: 7450a00ae4b3d4d72c7059b8835d6bbeec4399a8

URL: https://github.com/llvm/llvm-project/commit/7450a00ae4b3d4d72c7059b8835d6bbeec4399a8
DIFF: https://github.com/llvm/llvm-project/commit/7450a00ae4b3d4d72c7059b8835d6bbeec4399a8.diff

LOG: [msan] Add test for deferencing zero-sized malloc/calloc (#155934)

MSan fails to catch this, because 0-byte allocations are converted into
1-byte allocations.
    
Bug originally reported by dvyukov

Added: 
    compiler-rt/test/msan/zero_alloc.cpp

Modified: 
    

Removed: 
    


################################################################################
diff  --git a/compiler-rt/test/msan/zero_alloc.cpp b/compiler-rt/test/msan/zero_alloc.cpp
new file mode 100644
index 0000000000000..e60051872eba2
--- /dev/null
+++ b/compiler-rt/test/msan/zero_alloc.cpp
@@ -0,0 +1,39 @@
+// RUN: %clang_msan -Wno-alloc-size -fsanitize-recover=memory %s -o %t && not %run %t 2>&1 | FileCheck %s
+
+// MSan doesn't catch this because internally it translates 0-byte allocations
+// into 1-byte
+// XFAIL: *
+
+#include <malloc.h>
+#include <stdio.h>
+
+int main(int argc, char **argv) {
+  {
+    char *p1 = (char *)calloc(1, 0);
+    printf("p1 is %p\n", p1);
+    printf("Content of p1 is: %d\n", *p1);
+    // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
+    // CHECK: {{#0 0x.* in main .*zero_alloc.cpp:}}[[@LINE-2]]
+    free(p1);
+  }
+
+  {
+    char *p2 = (char *)calloc(0, 1);
+    printf("p2 is %p\n", p2);
+    printf("Content of p2 is: %d\n", *p2);
+    // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
+    // CHECK: {{#0 0x.* in main .*zero_alloc.cpp:}}[[@LINE-2]]
+    free(p2);
+  }
+
+  {
+    char *p3 = (char *)malloc(0);
+    printf("p3 is %p\n", p3);
+    printf("Content of p2 is: %d\n", *p3);
+    // CHECK: WARNING: MemorySanitizer: use-of-uninitialized-value
+    // CHECK: {{#0 0x.* in main .*zero_alloc.cpp:}}[[@LINE-2]]
+    free(p3);
+  }
+
+  return 0;
+}


        


More information about the llvm-commits mailing list