Fixes #46: ("UB due to union based type punning")

This commit is contained in:
Ion Gaztañaga
2020-01-16 16:10:03 +01:00
parent c66d25859b
commit d8761780b0
2 changed files with 12 additions and 10 deletions

View File

@@ -3886,6 +3886,13 @@ to be inserted in intrusive containers are allocated using `std::vector` or `std
[section:release_notes Release Notes] [section:release_notes Release Notes]
[section:release_notes_boost_1_73_00 Boost 1.73 Release]
* Fixed bugs:
* [@https://github.com/boostorg/intrusive/issues/46 GitHub #46: ['UB due to union based type punning]]
[endsect]
[section:release_notes_boost_1_71_00 Boost 1.71 Release] [section:release_notes_boost_1_71_00 Boost 1.71 Release]
* Fixed bugs: * Fixed bugs:

View File

@@ -24,6 +24,7 @@
#include <cstddef> #include <cstddef>
#include <climits> #include <climits>
#include <boost/intrusive/detail/mpl.hpp> #include <boost/intrusive/detail/mpl.hpp>
#include <cstring>
namespace boost { namespace boost {
namespace intrusive { namespace intrusive {
@@ -208,19 +209,13 @@ namespace detail {
//http://www.flipcode.com/archives/Fast_log_Function.shtml //http://www.flipcode.com/archives/Fast_log_Function.shtml
inline float fast_log2 (float val) inline float fast_log2 (float val)
{ {
union caster_t float f = val;
{ unsigned x;
unsigned x; std::memcpy(&x, &val, sizeof(f));
float val;
} caster;
caster.val = val;
unsigned x = caster.x;
const int log_2 = int((x >> 23) & 255) - 128; const int log_2 = int((x >> 23) & 255) - 128;
x &= ~(unsigned(255u) << 23u); x &= ~(unsigned(255u) << 23u);
x += unsigned(127) << 23u; x += unsigned(127) << 23u;
caster.x = x; std::memcpy(&val, &x, sizeof(f));
val = caster.val;
//1+log2(m), m ranging from 1 to 2 //1+log2(m), m ranging from 1 to 2
//3rd degree polynomial keeping first derivate continuity. //3rd degree polynomial keeping first derivate continuity.
//For less precision the line can be commented out //For less precision the line can be commented out