I was playing around with std::valarray and UndefinedBehaviorSanitizer, and noticed that std::begin an empty std::valarray causes undefined behavior. Here is the code:
#include <valarray>
int main() {
std::valarray<int> a;
std::begin(a);
}
To reproduce, compile the code with g++ -fsanitize=undefined and run the result executable.
Here is the std::begin implementation from libstdc++.
template<class _Tp>
inline _Tp*
begin(valarray<_Tp>& __va)
{ return std::__addressof(__va[0]); }
It seems that _val[0] creates an reference of null value for empty std::valarrays which causes the undefined behavior.
Is this a bug from libstdc++?