diff --git a/src/sfizz/modulations/ModMatrix.cpp b/src/sfizz/modulations/ModMatrix.cpp index 54e7a013..31707b5c 100644 --- a/src/sfizz/modulations/ModMatrix.cpp +++ b/src/sfizz/modulations/ModMatrix.cpp @@ -205,13 +205,20 @@ bool ModMatrix::connect(SourceId sourceId, TargetId targetId, float sourceDepth, if (sourceIndex >= impl.sources_.size() || targetIndex >= impl.targets_.size()) return false; + TargetId sourceDepthModId; + // We need to register the target _before_ taking a reference to target.connectedSources + // because if the targets_ vector is reallocated, all targets' connected sources will be moved + // and conn will point to freed memory. + if (sourceDepthMod) + sourceDepthModId = registerTarget(sourceDepthMod); + Impl::Target& target = impl.targets_[targetIndex]; Impl::ConnectionData& conn = target.connectedSources[sourceIndex]; conn.sourceDepth_ = sourceDepth; conn.sourceDepthMod_ = sourceDepthMod; - if (sourceDepthMod) - conn.sourceDepthModId_ = registerTarget(sourceDepthMod); + if (sourceDepthModId.valid()) + conn.sourceDepthModId_ = sourceDepthModId; conn.velToDepth_ = velToDepth; diff --git a/src/sfizz/modulations/ModMatrix.h b/src/sfizz/modulations/ModMatrix.h index 2aa59fe4..2586d257 100644 --- a/src/sfizz/modulations/ModMatrix.h +++ b/src/sfizz/modulations/ModMatrix.h @@ -57,6 +57,8 @@ public: * @brief Register a modulation source inside the matrix. * If it is already present, it just returns the existing id. * + * @note Might move the sources_ vector. + * * @param key source key * @param gen generator * @param flags source flags @@ -66,6 +68,8 @@ public: /** * @brief Register a modulation target inside the matrix. * + * @note Might move the targets_ vector. + * * @param key target key * @param region target region * @param flags target flags