Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch glaring undefined behavior statically?

I'm using clion and I'm running some code that has UB. My goal is to catch it statically:

#include <iostream>
#include <vector>



int main() {
    auto v = std::vector<int>();
    v.push_back(20);
    auto &first = v[0];
    auto vector_ref = &v;
    vector_ref->clear();
    std::cout << first;

}

This is UB, and I'm trying to catch it.

I have added the following to my cmake project:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=undefined -O1 -fno-omit-frame-pointer -g")

I still get no warnings.

what do I have to enable so that I can catch such UB instances?

like image 837
nz_21 Avatar asked Mar 03 '23 16:03

nz_21


1 Answers

Some compilers can detect some UB statically. No compiler is required to detect any UB except in some cases specified in the standard (in constant expressions).

what do I have to enable so that I can catch such UB instances?

Best you can do is to enable all warnings. If the compiler doesn't detect it, then modify the compiler to do so. This may be either very difficult, or very expensive in compile time, or both.

Sanitisers can help only at runtime.

like image 160
eerorika Avatar answered Mar 27 '23 23:03

eerorika