bugfix: string_view of invalid memory (#23417)

### Description

the `std::unordered_map` uses a `std::string_view` as key, while the
string view may refer to invalid memory. Function `IdentityBuilder`
returns a `std::string` which goes out of scope quickly.

```c++
  unordered_map<string_view, std::vector<NodeIndex>> identical_children_map;
  for (auto i = node->OutputEdgesBegin(); i != node->OutputEdgesEnd(); ++i) {
    if (i->GetNode().OpType() == op) {
      identical_children_map[IdentityBuilder(graph, i->GetNode())].push_back(i->GetNode().Index());
    }
  }
```

This code will cause a waring as error in EMSDK v4.0.1:

```
C:/code/o2/onnxruntime/core/optimizer/identical_children_consolidation.cc:51:30: error: object whose reference is captured by 'identical_children_map' will be destroyed at the end of the full-expression [-Werror,-Wdangling-capture]
   51 |       identical_children_map[IdentityBuilder(graph, i->GetNode())].push_back(i->GetNode().Index());
      |                              ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1 error generated.
```
This commit is contained in:
Yulong Wang 2025-01-17 07:56:26 -08:00 committed by GitHub
parent b8599b786e
commit a350040aa7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -45,7 +45,7 @@ std::vector<std::vector<NodeIndex>> IdenticalChildrenConsolidation::DivideIdenti
const Graph& graph,
Node* node,
const string_view& op) {
unordered_map<string_view, std::vector<NodeIndex>> identical_children_map;
unordered_map<std::string, std::vector<NodeIndex>> identical_children_map;
for (auto i = node->OutputEdgesBegin(); i != node->OutputEdgesEnd(); ++i) {
if (i->GetNode().OpType() == op) {
identical_children_map[IdentityBuilder(graph, i->GetNode())].push_back(i->GetNode().Index());
@ -125,4 +125,4 @@ std::string IdenticalChildrenConsolidation::IdentityBuilder(const Graph& graph,
return identity.str();
}
} // namespace onnxruntime
} // namespace onnxruntime