diff --git a/Changelog.md b/Changelog.md index 12af786..d7d579f 100644 --- a/Changelog.md +++ b/Changelog.md @@ -4,6 +4,10 @@ SPDX-FileCopyrightText: 2026 Jan Kleinert SPDX-License-Identifier: Apache-2.0 --> +# Unreleased + +- Fix undefined behaviour in `DAGNode::~DAGNode()`, which erased from the parent list while iterating over it (#86) + # v0.3.5 - First open source version! diff --git a/parametric/dag.hpp b/parametric/dag.hpp index e9eb426..fe60e7f 100644 --- a/parametric/dag.hpp +++ b/parametric/dag.hpp @@ -316,14 +316,14 @@ class DAGNode */ virtual bool IsValid() const { return false; }; - virtual ~DAGNode() - { - for (const auto& parent : parents) { - if (parent) { - remove_parent(*parent); - } - } - } + /** + * @brief Destroys the node. + * + * The parent list is released together with the node. Entries in the parents' child lists + * are deliberately left in place: they are weak pointers that simply expire, and compute nodes + * rely on them as positional output slots (see ComputeNode::res). + */ + virtual ~DAGNode() = default; using ClonedNodeMap = std::unordered_map>; /**< @private */ static std::shared_ptr new_cloned_node_map() { diff --git a/tests/dag.cpp b/tests/dag.cpp index faea66c..7a4955a 100644 --- a/tests/dag.cpp +++ b/tests/dag.cpp @@ -73,4 +73,40 @@ TEST(DAG, unattach) a->remove_parent(*b); EXPECT_FALSE(b->precedes(*a)); EXPECT_TRUE(b->precedes(*c)); -} \ No newline at end of file +} +// Destroying a node must not modify the parent list it iterates over (UB, flagged by ASan with +// -D_GLIBCXX_SANITIZE_VECTOR). See https://github.com/grunk-dev/parametric/issues/86 +TEST(DAG, destroyNodeWithParents) +{ + NodeRef x(new DAGNode("x")); + NodeRef y(new DAGNode("y")); + { + NodeRef z(new DAGNode("z")); + NodeRef w(new DAGNode("w")); + add_parent(z, x); + add_parent(z, y); + add_parent(w, z); + add_parent(w, x); + EXPECT_EQ(2, w->num_parents()); + } + // the surviving parents are still intact and usable + EXPECT_EQ(0, x->num_parents()); + EXPECT_EQ(0, y->num_parents()); + NodeRef c(new DAGNode("c")); + add_parent(c, x); + EXPECT_TRUE(x->precedes(*c)); +} + +TEST(DAG, destroyNodeWithDuplicateParents) +{ + NodeRef a(new DAGNode("a")); + { + NodeRef b(new DAGNode("b")); + add_parent(b, a); + add_parent(b, a); + EXPECT_EQ(2, b->num_parents()); + } + NodeRef c(new DAGNode("c")); + add_parent(c, a); + EXPECT_TRUE(a->precedes(*c)); +}