Skip to content

Commit 8adbd1c

Browse files
authored
Prevent buffer overflow when assigning to fixed-dimension xtensor with mismatched rank (#2907)
# Checklist - [x] The title and commit message(s) are descriptive. - [x] Small commits made to fix your PR have been squashed to avoid history pollution. - [x] Tests have been added for new features or bug fixes. - [x] API of new functions and classes are documented. # Description Addressing #2792 Assigning a higher-dimensional expression to a fixed-rank [xtensor<T, N>] caused a buffer overflow (stack smashing) in release builds: ```c++ auto a = xt::xtensor<float, 1>::from_shape({2}); a = xt::expand_dims(a, 0); // expand_dims returns 2D view, shape {1, 2} // buffer overflow: resize truncates shape {1,2} -> {1}, then copies 2 elements into 1 element buffer ``` --------- Co-authored-by: Alexis Placet <2400067+Alex-PLACET@users.noreply.github.com>
1 parent 2b01100 commit 8adbd1c

2 files changed

Lines changed: 9 additions & 2 deletions

File tree

include/xtensor/containers/xcontainer.hpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -997,10 +997,10 @@ namespace xt
997997
template <class S>
998998
inline void xstrided_container<D>::resize(S&& shape, bool force)
999999
{
1000-
XTENSOR_ASSERT_MSG(
1000+
XTENSOR_PRECONDITION(
10011001
detail::check_resize_dimension(m_shape, shape),
10021002
"cannot change the number of dimensions of xtensor"
1003-
)
1003+
);
10041004
std::size_t dim = shape.size();
10051005
if (m_shape.size() != dim || !std::equal(std::begin(shape), std::end(shape), std::begin(m_shape))
10061006
|| force)

test/test_xassign.cpp

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
#include "xtensor/containers/xtensor.hpp"
1616
#include "xtensor/core/xassign.hpp"
1717
#include "xtensor/core/xnoalias.hpp"
18+
#include "xtensor/misc/xmanipulation.hpp"
1819

1920
#include "test_common.hpp"
2021
#include "test_common_macros.hpp"
@@ -167,4 +168,10 @@ namespace xt
167168
EXPECT_EQ(a.shape(1), 3);
168169
}
169170
}
171+
172+
TEST(xassign, fixed_dimension_mismatch)
173+
{
174+
auto a = xt::xtensor<float, 1>::from_shape({2});
175+
XT_ASSERT_THROW(a = xt::expand_dims(a, 0), std::runtime_error);
176+
}
170177
}

0 commit comments

Comments
 (0)