Fix crash in LIB_SYMBOL::SetUnitCount when reducing unit count

When decreasing the number of units in a symbol, the previous code erased
items directly from m_drawings using a single iterator. Because m_drawings
is a MULTIVECTOR, this could invalidate iterators and attempt to erase
from the wrong bucket, leading to segmentation faults.

This patch iterates bucket by bucket and erases items belonging to units
greater than the requested count. This ensures iterator safety and avoids
accessing invalid memory.

Fixes https://gitlab.com/kicad/code/kicad/-/issues/21631
This commit is contained in:
Adrián García 2025-09-05 16:44:45 +02:00 committed by Seth Hillbrand
parent 6f352ccd96
commit fb558eee3c

View File

@ -1327,14 +1327,18 @@ void LIB_SYMBOL::SetUnitCount( int aCount, bool aDuplicateDrawItems )
if( aCount < m_unitCount )
{
LIB_ITEMS_CONTAINER::ITERATOR i = m_drawings.begin();
while( i != m_drawings.end() )
// Iterate each drawing-type bucket and erase items that belong to units > aCount.
for( int type = LIB_ITEMS_CONTAINER::FIRST_TYPE; type <= LIB_ITEMS_CONTAINER::LAST_TYPE; ++type )
{
if( i->m_unit > aCount )
i = m_drawings.erase( i );
else
++i;
auto it = m_drawings.begin( type );
while( it != m_drawings.end( type ) )
{
if( it->m_unit > aCount )
it = m_drawings.erase( it ); // returns next iterator
else
++it;
}
}
}
else if( aDuplicateDrawItems )