In a naive reference-counting smart pointer implementation, the reference-counter could overflow. How is this overflow avoided or handled in C++ standard library implementations?
1 Answer
Snippets from stdlibc++ headers:
typedef int _Atomic_word;
class _Sp_counted_base
/*snip*/
_Atomic_word _M_use_count;
/*snip*/
_M_weak_add_ref()
{ __gnu_cxx::__atomic_add_dispatch(&_M_weak_count, 1); }
/*snip*/
__atomic_add_dispatch(/*snip*/)
{
/*snip*/
__atomic_add_single(/*snip*/);
/*snip*/
}
__atomic_add_single(/*snip*/)
{ *__mem += __val; }
Conclusion: This particular implementation "handles" reference-counter overflow by ignoring the possibility.
4 Comments
NathanOliver
It is surprising that they use an
int but I is hard, for me at least, to envision a use case for 32767 pointers to the same thing.Bob Jansen
In general yes, but what if an attacker manages to produce some malicious input that causes the program to create them?
eerorika
@BobJansen that could be bad. Another conclusion: You should not let user input directly affect the number of shared pointers without a bound. In fact, I would extend this to anything that allocates memory (or other resources).
zett42
I just had a look at the MSVC++2017 implementation of
std::shared_ptr. They call _InterlockedIncrement() which overflows aswell.
size_tthen they should not be able to allocate enough pointers to overflow that.std::shared_ptr's function to return the reference counter returns along, so I guess that is the "soft" limit.