A static coding style checker for detecting API misuses of C++ smart pointers that will probably lead to memory errors like memory leak, use after free, and double free.
clang-tidy with SPrinter (SHA256SUM cc04e23416ef3896fd5c6a37b8d0f0757b41e10197cb171b0890ffe0e3d1466f)
Source code repository: https://github.com/Snape3058/SPrinter
Build SPrinter: Build LLVM with subproject clang and
clang-tools-extra enabled by following the LLVM CMake build
instruction: https://releases.llvm.org/9.0.0/docs/CMake.html
tl;dr:
/path/to/sprinter-root/build$ cmake ../llvm -DLLVM_ENABLE_PROJECTS=clang;clang-tools-extra
/path/to/sprinter-root/build$ make clang-tidy
smartpointersafety-
prefix for all the error patterns mentioned above.E.g.
$ clang-tidy -checks='-*,smartpointersafety-*' source.cppReport an auto_ptr template argument used in an STL
container.
std::vector<std::auto_ptr<int>> vi;
^
Warn hereReport all the memory transfer from one auto_ptr to
another.
std::auto_ptr<int> p1(new int(42));
void foo(std::auto_ptr<int> p);
foo(p1);
^
Warn hereReport the operation that deletes the pointer from smart
pointer observers.
std::unique_ptr<int> p = std::make_unique<int>(42);
delete p.get();
^
Warn hereReport the initiations with non-allocated memory.
int I;
std::unique_ptr<int> p(&I);
^
Warn hereReport a private auto_ptr field in a class without copy
constructors and assignment operators.
class Type {
private:
std::auto_ptr<int> p;
^
Warn here
};Report the construction of a smart pointer with a raw pointer variable.
void foo(int *p) {
std::unique_ptr<int> sp(p);
^
Warn here
}Report the mismatched type of template argument and new
operator for smart pointer constructions.
std::auto_ptr<int> sp(new int[42]);
^
Warn hereReport the usages of unchecked locked weak_ptrs.
std::weak_ptr<int> wp;
...
*wp.lock() = 42;
^
Warn hereReport the released pointer that are not dealocated.
std::unique_ptr<int> sp;
...
*sp.release() = 42;
^
Warn hereThe open-source projects used in Table III are listed as follows.