Skip to content

Commit 80add81

Browse files
ai-edge-botcopybara-github
authored andcommitted
Fix undefined behavior in model.h.
The function LiteRtTensorT::NumElements() was assuming that decltype(dims[0])=`const int` if dims is a const reference to an array of ints. In fact, it's `const int&`. The effect is a difference in behavior between optimized and non-optimized builds. LiteRT-PiperOrigin-RevId: 819888199
1 parent 555a7fe commit 80add81

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

litert/core/model/model.h

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#include <numeric>
2626
#include <optional>
2727
#include <string>
28+
#include <type_traits>
2829
#include <unordered_map>
2930
#include <utility>
3031
#include <variant>
@@ -389,9 +390,9 @@ class LiteRtTensorT {
389390
return 0;
390391
}
391392
const auto& dims = ranked->layout.dimensions;
392-
return static_cast<size_t>(
393-
std::accumulate(std::cbegin(dims), std::cend(dims), 1,
394-
std::multiplies<decltype(dims[0])>()));
393+
return static_cast<size_t>(std::accumulate(
394+
std::cbegin(dims), std::cend(dims), 1,
395+
std::multiplies<std::remove_reference_t<decltype(dims[0])>>()));
395396
}
396397

397398
// Set the tensor type.

litert/core/model/model_test.cc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,7 @@ TEST(ModelSubgraphTest, Input) {
166166
LiteRtSubgraphT subgraph;
167167
subgraph.Inputs().push_back(&tensor);
168168
EXPECT_EQ(&subgraph.Input(0), subgraph.Inputs().front());
169+
EXPECT_EQ(tensor.NumElements(), 0);
169170
}
170171

171172
TEST(ModelSubgraphTest, Output) {

0 commit comments

Comments
 (0)