Linaro / OpenCSD

CoreSight trace stream decoder developed openly
https://github.com/Linaro/opencsd/wiki
Other
143 stars 54 forks source link

Invalidated iterator is used in EtmV4P0Stack::erase_curr_from_front() #58

Closed yabinc closed 1 year ago

yabinc commented 1 year ago

In https://github.com/Linaro/OpenCSD/blob/master/decoder/source/etmv4/trc_etmv4_stack_elem.cpp#L190:

void EtmV4P0Stack::erase_curr_from_front() { std::deque<TrcStackElem *>::iterator erase_iter; erase_iter = m_iter; erase_iter--; m_P0_stack.erase(erase_iter);

// explicitly delete the item here as the caller can no longer reference it.
// fixes memory leak from github issue #52
delete *erase_iter;

}

We fix the memory leak by "delete *erase_iter". But the element pointed by erase_iter is erased in "m_P0_stack.erase(erase_iter);". The erase() method can invalidate erase_iter iterator, as suggested in the "Iterator invalidation " section in https://en.cppreference.com/w/cpp/container/vector.

The error was detected by ubsan. It can be fixed by below change: { ... TrcStackElem elem = erase_iter; m_iter = m_P0_stack.erase(erase_iter);

// explicitly delete the item here as the caller can no longer reference it.
// fixes memory leak from github issue #52
delete elem;

}

yabinc commented 1 year ago

Thanks for the fix!