http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57997
Bug ID: 57997 Summary: Segmentation fault after returning valarray expression from an auto function Product: gcc Version: 4.8.1 Status: UNCONFIRMED Severity: major Priority: P3 Component: libstdc++ Assignee: unassigned at gcc dot gnu.org Reporter: roystgnr at ices dot utexas.edu The following code: //////// #include <valarray> template<typename T> auto f1(const T& x, const T& y) -> decltype(x*y/2) { return x*y/2; } int main() { std::valarray<float> a(4, 1); std::valarray<float> b(4, 1); std::valarray<float> c(4, 1); c = a*b/2; c = f1(a,b); return 0; } //////// compiled with g++ 4.8.1 (-std=c++11), dies at runtime with a segmentation fault, stack trace: (gdb) where #0 0x0000000000400e60 in std::__multiplies::operator()<float> (this=0x7fffffffd95f, __x=@0x0: <error reading variable>, __y=@0x603030: 4) at /usr/include/c++/4.8/bits/valarray_before.h:204 #1 0x0000000000400ddc in std::_BinBase<std::__multiplies, std::valarray<float>, std::valarray<float> >::operator[] (this=0x7fffffffda50, __i=0) at /usr/include/c++/4.8/bits/valarray_before.h:524 #2 0x0000000000400d4d in std::_BinBase2<std::__divides, std::_BinClos<std::__multiplies, std::_ValArray, std::_ValArray, float, float> >::operator[] (this=0x7fffffffdac0, __i=0) at /usr/include/c++/4.8/bits/valarray_before.h:545 #3 0x0000000000400d0b in std::_Expr<std::_BinClos<std::__divides, std::_Expr, std::_Constant, std::_BinClos<std::__multiplies, std::_ValArray, std::_ValArray, float, float>, float>, float>::operator[] (this=0x7fffffffdac0, __i=0) at /usr/include/c++/4.8/bits/valarray_after.h:216 #4 0x0000000000400c40 in std::__valarray_copy<float, std::_BinClos<std::__divides, std::_Expr, std::_Constant, std::_BinClos<std::__multiplies, std::_ValArray, std::_ValArray, float, float>, float> > (__e=..., __n=1, __a=...) at /usr/include/c++/4.8/bits/valarray_array.tcc:146 #5 0x0000000000400a75 in std::valarray<float>::operator=<std::_BinClos<std::__divides, std::_Expr, std::_Constant, std::_BinClos<std::__multiplies, std::_ValArray, std::_ValArray, float, float>, float> > (this=0x7fffffffdaa0, __e=...) at /usr/include/c++/4.8/valarray:823 #6 0x000000000040083c in main () at test.C:16 Examination in gdb of the expression template returned by f1 shows member values which seem to be correct immediately after the return but which become corrupted during the operator= evaluation. I can't be sure, but it seems as if sufficiently complicated expression templates (removing "/2" from the above code doesn't trigger the problem) may be saving references to stack-allocated (i.e. temporary, later overwritten) subexpressions. My colleague reports being able to reproduce the problem (albeit on our original code, not the above distilled testcase) with gcc trunk r201275. The problem seems to lie with the valarray headers; using clang++ 3.3 with libstdc++ results in the same failure, whereas the clang++/libc++ combination passes our tests.