8

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?

12
  • 8
    I'm not sure you could overflow the reference count. If they used size_t then they should not be able to allocate enough pointers to overflow that. Commented May 22, 2017 at 14:43
  • 4
    std::shared_ptr's function to return the reference counter returns a long, so I guess that is the "soft" limit. Commented May 22, 2017 at 14:45
  • 8
    That's a real concern. If you generate a new reference every nanosecond, you would overflow a 64-bit count in less than 600 years. Commented May 22, 2017 at 14:51
  • 4
    @stark and your pointers would consume more memory than can be addressed by a 64 bit pointer :) Commented May 22, 2017 at 14:52
  • 6
    If your program overflows a reference counter, you probably deserve it. Commented May 22, 2017 at 15:19

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.
In general yes, but what if an attacker manages to produce some malicious input that causes the program to create them?
@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).
I just had a look at the MSVC++2017 implementation of std::shared_ptr. They call _InterlockedIncrement() which overflows aswell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.