2

Two simplified examples:

#include <cstdlib>
#include <string>
#include <vector>

class Object{};

void use1(Object * o)
{
    (void)(o);
}

void use2(std::string & s)
{
    (void)(s);
}

int f1()
{
    Object * object_ptr{ nullptr };
    {
        Object object{};
        object_ptr = &object;
    }
    use1(object_ptr); // UB
    return rand();
}

int f2()
{
    std::vector<std::string> v{"foo", "bar"};
    auto & v_ref = v[0];
    v.emplace_back("baz");
    use2(v_ref); // UB
    return rand();
}

int main()
{
    return f1() + f2();
}

(rand() is just for testing.)

Rust just can not compile sources like this. With Clang or GCC (or maybe MSVC?) is there an option to detect such an undefined behavior?

vladon
  • 8,158
  • 2
  • 47
  • 91
  • 3
    Possible dupe/related: [A C++ implementation that detects undefined behavior?](http://stackoverflow.com/questions/7237963/a-c-implementation-that-detects-undefined-behavior) – NathanOliver Jan 11 '16 at 13:24
  • 1
    rust has *lifetime* in its type, c++ doesn't have it. – Jarod42 Jan 11 '16 at 13:26
  • 3
    If you look at the mailing lists, a lifetime checker is currently on the way in clang static analyser: http://lists.llvm.org/pipermail/cfe-dev/2015-December/046653.html – Guillaume Racicot Jan 11 '16 at 13:29
  • @GuillaumeRacicot Just checking available tools: PVS-Studio can detect first UB (`V506 Pointer to local variable 'object' is stored outside the scope of this variable. Such a pointer will become invalid.`), but cannot detect second. Cppcheck also can detect first (`Dead pointer usage`), but cannot detect second. – vladon Jan 11 '16 at 13:48

1 Answers1

2

Out of the box, no you can't. C++ is not like rust and give you the power of shooting yourself on the foot.

Fortunately, static analyser can detect errors for you. And with the clang static analyser, a lifetime checker is definitely on the way link to the mailing list message and may suit your needs.

If you have memory errors, you can detect them with valgrind, it has been useful for me time to time.

Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141