xref: /llvm-project/clang/test/Analysis/malloc-std-namespace.cpp (revision 893a303962608469ec5bd01fe44e82c935152e9c)
1d6d84b5dSNagyDonat // RUN: %clang_analyze_cc1 -analyzer-checker=core,unix.Malloc -verify -analyzer-output=text %s
2d6d84b5dSNagyDonat 
3d6d84b5dSNagyDonat // This file tests that unix.Malloc can handle C++ code where e.g. malloc and
4d6d84b5dSNagyDonat // free are declared within the namespace 'std' by the header <cstdlib>.
5d6d84b5dSNagyDonat 
6d6d84b5dSNagyDonat #include "Inputs/system-header-simulator-cxx.h"
7d6d84b5dSNagyDonat 
8d6d84b5dSNagyDonat void leak() {
9d6d84b5dSNagyDonat   int *p = static_cast<int*>(std::malloc(sizeof(int))); // expected-note{{Memory is allocated}}
10d6d84b5dSNagyDonat } // expected-warning{{Potential leak of memory pointed to by 'p'}}
11d6d84b5dSNagyDonat   // expected-note@-1{{Potential leak of memory pointed to by 'p'}}
12d6d84b5dSNagyDonat 
13d6d84b5dSNagyDonat void no_leak() {
14d6d84b5dSNagyDonat   int *p = static_cast<int*>(std::malloc(sizeof(int)));
15d6d84b5dSNagyDonat   std::free(p); // no-warning
16d6d84b5dSNagyDonat }
17d6d84b5dSNagyDonat 
18d6d84b5dSNagyDonat void invalid_free() {
19d6d84b5dSNagyDonat   int i;
20d6d84b5dSNagyDonat   int *p = &i;
21*893a3039SPavel Skripkin   //expected-note@+2{{Argument to 'free()' is the address of the local variable 'i', which is not memory allocated by 'malloc()'}}
22*893a3039SPavel Skripkin   //expected-warning@+1{{Argument to 'free()' is the address of the local variable 'i', which is not memory allocated by 'malloc()'}}
23d6d84b5dSNagyDonat   std::free(p);
24d6d84b5dSNagyDonat }
25