[cfe-dev] [Clang Static Analyzer] Lifetime checker

Bhargava Shastry via cfe-dev cfe-dev at lists.llvm.org
Mon Dec 21 01:56:49 PST 2015


Hi all,

I am starting work on a cppcoreguidelines [1] checker related to object
lifetime in C++ code. In the long term, the idea is to make the
`NewDeleteChecker` more robust by modeling STL functions. Afaik, the
`NewDeleteChecker` already catches local use-after-free and mem-leak
bugs. However, as [1] suggests, the long-term view is to conservatively
flag scenarios where dangling pointers can be created.

After experimenting with Clang SA checkers, I concluded that in the
short term, it would be nice to model lifetime of stack vars. Something
as simple as the following example:

```
cpp
1 #include <cstddef>
2 void f() {
3 int* p = NULL;
4 {
5 int i = 0;
6 p = &i;
7 *p = 42; // ok
8 } // i's lifetime ends here
9 *p = 1; // ERROR, p was invalidated when i went out of scope
10 }
```

The `StackAddressEscape` checker flags a warning when the address of a
stack-local variable is returned or assigned to a global. But there
lifetime is `modeled` by simply checking if addresses can escape a stack
frame. More fine-grained checking (scopes) is missing.

Questions:
1. Why doesn't Clang SA proper not mark `i` as dead on Line 9?
2. What is the missing code that can link `i`'s lifetime to validity of `p`?

I would be happy to contribute patches to catch this simple case.

[1]:
https://github.com/isocpp/CppCoreGuidelines/blob/master/docs/Lifetimes%20I%20and%20II%20-%20v0.9.1.pdf

Regards
Bhargava


More information about the cfe-dev mailing list