Opened 8 years ago
Last modified 8 years ago
#10337 new Bugs
weak_ptr & shared_ptr causes double "delete" -> crash
Reported by: | Owned by: | Peter Dimov | |
---|---|---|---|
Milestone: | To Be Determined | Component: | smart_ptr |
Version: | Boost 1.53.0 | Severity: | Problem |
Keywords: | Cc: |
Description
I am not sure why this happens (VS2005 - VS2013) and specifically on windows (code compiles and runs fine on linux)...
The following is the boost code that is responsible:
void sp_counted_impl_p<T>::release() nothrow {
if( BOOST_INTERLOCKED_DECREMENT( &use_count_ ) == 0 ) {
dispose(); weak_release();
}
}
void sp_counted_impl_p<T>::weak_release() nothrow {
if( BOOST_INTERLOCKED_DECREMENT( &weak_count_ ) == 0 ) {
destroy();
}
}
Look what MUST happen, when "use_count = 1" and "weak_count = 1".. It causes a double release which crashes the application. That was a real pain in the ass to track down and unfortunately I have nothing to specifically trigger this issue either. Just look at the code and it should be obvious that this is a race condition.
Yeah I can now tell this issue persists in 1.56... Also I found a bug in my code. The issue was that I had two shared_ptr of which one was using a weak_ptr to the other. Then the one the weak_ptr pointed to got release by C++ before the other, so that the race condition above happened. I still think this should be fixed, because its obviously a race condition in boost too.
I solved the issue on my end by simply turning the weak_ptr into a shared_ptr and the original shared_ptr that the weak_ptr pointed to into a weak_ptr. This will force the correct release order at application exit upon boost and prevents the race condition from happening.