Skip to content

std::valarray lacks size assertion when using multiple chained operator+ calls #153518

@hutuhutong

Description

@hutuhutong

Product / Version: clang20.1.0

-Os -std=c++20 -D_GLIBCXX_ASSERTIONS

This issue affects all versions of libstdc++. Since Clang, by default, relies on the system’s libstdc++ implementation, the same behavior is observed when using Clang with libstdc++. When using libc++, neither of the two lines triggers the assertion failure. I am not certain whether libc++ includes a similar length check for __v.size() == __w.size(), but it is clear that future versions of Clang should take note of updates in libstdc++ regarding this issue. you can see the problem in https://godbolt.org/z/qfKTKazbo.
========== code ==========

#include <valarray>
#include <iostream>
using namespace std;

int main() {
    typedef std::valarray<int> A;
    A a(3, 2), b(3, 2), e(1, 3);

    // This line does not trigger assertion failure
    A c = a + b + e;

    // This line triggers assertion failure
    // A c = a + e;

    A d = c;
    printf("Result array size: %zu\n", d.size());

    return 0;
}

========== output ==========
when A c = a + b + e is executed, the program is normal;

When a + e is executed, the program crashes:

/opt/compiler-explorer/gcc-14.2.0/lib/gcc/x86_64-linux-gnu/14.2.0/../../../../include/c++/14.2.0/valarray:1196: _Expr<_BinClos<__plus, _ValArray, _ValArray, _Tp, _Tp>, typename __fun<__plus, _Tp>::result_type> std::operator+(const valarray<_Tp> &, const valarray<_Tp> &) [_Tp = int]: Assertion '__v.size() == __w.size()' failed.
Program terminated with signal: SIGSEGV

Metadata

Metadata

Assignees

No one assigned

    Labels

    hardeningIssues related to the hardening effortlibc++libc++ C++ Standard Library. Not GNU libstdc++. Not libc++abi.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions