xref: /minix3/external/bsd/llvm/dist/clang/test/Analysis/malloc-sizeof.cpp (revision 0a6a1f1d05b60e214de2f05a7310ddd1f0e590e7)
1*0a6a1f1dSLionel Sambuc // RUN: %clang_cc1 -analyze -analyzer-checker=unix.MallocSizeof -verify %s
2*0a6a1f1dSLionel Sambuc 
3*0a6a1f1dSLionel Sambuc #include <stddef.h>
4*0a6a1f1dSLionel Sambuc 
5*0a6a1f1dSLionel Sambuc void *malloc(size_t size);
6*0a6a1f1dSLionel Sambuc void *calloc(size_t nmemb, size_t size);
7*0a6a1f1dSLionel Sambuc void *realloc(void *ptr, size_t size);
8*0a6a1f1dSLionel Sambuc void free(void *ptr);
9*0a6a1f1dSLionel Sambuc 
10*0a6a1f1dSLionel Sambuc struct A {};
11*0a6a1f1dSLionel Sambuc struct B {};
12*0a6a1f1dSLionel Sambuc 
foo(unsigned int unsignedInt,unsigned int readSize)13*0a6a1f1dSLionel Sambuc void foo(unsigned int unsignedInt, unsigned int readSize) {
14*0a6a1f1dSLionel Sambuc   // Sanity check the checker is working as expected.
15*0a6a1f1dSLionel Sambuc   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*0a6a1f1dSLionel Sambuc   free(a);
17*0a6a1f1dSLionel Sambuc }
18*0a6a1f1dSLionel Sambuc 
bar()19*0a6a1f1dSLionel Sambuc void bar() {
20*0a6a1f1dSLionel Sambuc   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*0a6a1f1dSLionel Sambuc   // sizeof(void*) is compatible with any pointer.
22*0a6a1f1dSLionel Sambuc   A **y = static_cast<A**>(calloc(10, sizeof(void*))); // no-warning
23*0a6a1f1dSLionel Sambuc   free(x);
24*0a6a1f1dSLionel Sambuc   free(y);
25*0a6a1f1dSLionel Sambuc }
26*0a6a1f1dSLionel Sambuc 
27