xref: /aosp_15_r20/external/clang/test/Analysis/malloc-sizeof.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li // RUN: %clang_cc1 -analyze -analyzer-checker=unix.MallocSizeof -verify %s
2*67e74705SXin Li 
3*67e74705SXin Li #include <stddef.h>
4*67e74705SXin Li 
5*67e74705SXin Li void *malloc(size_t size);
6*67e74705SXin Li void *calloc(size_t nmemb, size_t size);
7*67e74705SXin Li void *realloc(void *ptr, size_t size);
8*67e74705SXin Li void free(void *ptr);
9*67e74705SXin Li 
10*67e74705SXin Li struct A {};
11*67e74705SXin Li struct B {};
12*67e74705SXin Li 
foo(unsigned int unsignedInt,unsigned int readSize)13*67e74705SXin Li void foo(unsigned int unsignedInt, unsigned int readSize) {
14*67e74705SXin Li   // Sanity check the checker is working as expected.
15*67e74705SXin Li   A* a = static_cast<A*>(malloc(sizeof(int))); // expected-warning {{Result of 'malloc' is converted to a pointer of type 'struct A', which is incompatible with sizeof operand type 'int'}}
16*67e74705SXin Li   free(a);
17*67e74705SXin Li }
18*67e74705SXin Li 
bar()19*67e74705SXin Li void bar() {
20*67e74705SXin Li   A *x = static_cast<A*>(calloc(10, sizeof(void*))); // expected-warning {{Result of 'calloc' is converted to a pointer of type 'struct A', which is incompatible with sizeof operand type 'void *'}}
21*67e74705SXin Li   // sizeof(void*) is compatible with any pointer.
22*67e74705SXin Li   A **y = static_cast<A**>(calloc(10, sizeof(void*))); // no-warning
23*67e74705SXin Li   free(x);
24*67e74705SXin Li   free(y);
25*67e74705SXin Li }
26*67e74705SXin Li 
27