Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strict aliasing violation

Does the following program violate the strict aliasing rule?

#include <cstdint>

int main()
{
    double d = 0.1;

    //std::int64_t n = *reinterpret_cast<std::int64_t*>(&d); // aliasing violation

    //auto n{*reinterpret_cast<std::int64_t*>(&d)}; // aliasing violation

    auto nptr{reinterpret_cast<std::int64_t*>(&d)};
    auto& n{*nptr};

    ++n;
}

No warning emitted by VS2015, clang or gcc.

like image 528
wally Avatar asked Jun 23 '16 17:06

wally


2 Answers

Does the following program violate the strict aliasing rule?

Yes, it does. You are dereferencing a double* (&d) using a std::int64_t*.

The line that violates strict aliasing rule is:

auto& n{*nptr};

While processing the line, the compilers don't necessarily know how you set the value of nptr. The fact that it is an alias to a double* is not obvious while processing that line.

like image 153
R Sahu Avatar answered Sep 19 '22 10:09

R Sahu


Yes, this violates strict aliasing. You are accessing an object d of type double, though a pointer nptr which is not a pointer to double or any type related to it.

Just because a compiler does not emit a warning does not mean it isn't a violation. Violations of strict arising are UB (since they're a matter of runtime behavior) and therefore do not require a diagnostic.

like image 22
Nicol Bolas Avatar answered Sep 20 '22 10:09

Nicol Bolas