[LLVMbugs] [Bug 21102] New: Warn/static-analysis diagnostic on passing reference to objects that may be invalidated

bugzilla-daemon at llvm.org bugzilla-daemon at llvm.org
Tue Sep 30 14:41:22 PDT 2014


http://llvm.org/bugs/show_bug.cgi?id=21102

            Bug ID: 21102
           Summary: Warn/static-analysis diagnostic on passing reference
                    to objects that may be invalidated
           Product: clang
           Version: trunk
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P
         Component: Static Analyzer
          Assignee: kremenek at apple.com
          Reporter: seth.cantrell at gmail.com
                CC: llvmbugs at cs.uiuc.edu
    Classification: Unclassified

In his presentation 'Back to the Basics! Essentials of Modern C++ Style'[1]
Herb Sutter calls out one case of using smart pointers that can cause object
lifetime errors:

    #include <memory>
    #include <cassert>
    #include <vector>

    struct widget { std::vector<int> v {1,2,3}; };

    std::shared_ptr<widget> g_p = std::make_shared<widget>();

    void g() {
      g_p = nullptr;
    }

    void use(widget &w) {
      assert(w.v.size() == 3);
    }

    void f(widget &w) {
      g();
      use(w);
    }

    int main() {
      f(*g_p);
    }

The above program invokes undefined behavior by accessing an object through an
invalidated reference.

Herb argues that the code `f(*g_p)` should not pass code reviews and that this
problem should be statically detectable (at 25 to 27 minutes into his
presentation [2]). It would be nice to have this automated check, as a compiler
warning if possible, but at least as a static analyzer check.

Furthermore, the same error can happen with non-smart-pointer managed objects.
Here's an example that the analyzer doesn't currently catch but which might be
usefully caught:

    #include <cassert>

    int *p;

    void g() {
      *p = 0;
      delete p;
      p = nullptr;
    }

    void use(int &i) {
      assert(i == 10);
    }

    void f(int &i) {
      g();
      use(i);
    }

    int main() {
      p = new int{10}
      f(*p);
    }

[1]:
https://github.com/CppCon/CppCon2014/tree/master/Presentations/Back%20to%20the%20Basics!%20Essentials%20of%20Modern%20C%2B%2B%20Style
[2]: https://www.youtube.com/watch?v=xnqTKD8uD64

-- 
You are receiving this mail because:
You are on the CC list for the bug.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/llvm-bugs/attachments/20140930/1aeaa9e1/attachment.html>


More information about the llvm-bugs mailing list