Search code examples
c++gccclangundefined-behaviorcompiler-options

Detect UB like Rust


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?


Solution

  • 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.