Search code examples
c++pointersallocatordelete-operator

Why is a pointer not permitted to be null when calling the deallocate method of the allocator class?


I can across this while reading C++ Primer:

The pointer we pass to deallocate cannot be null; it must point to memory allocated by allocate.

I checked the source of deallocate and found this:

// __p is not permitted to be a null pointer.
void
deallocate(pointer __p, size_type)
{ ::operator delete(__p); }

Ok, so I know there is a distinction between the delete expression and operator delete(). The delete expression can be used on a null pointer. However, this function calls the global operator delete() function directly. However, I googled this problem and found a blog post here that also states the global operator delete method checks for null pointers as well, like this:

void
operator delete (void* ptr) throw ()
{
  if (ptr)
    std::free (ptr);
}

Also, ironically, I also found here that calling std::free on a null pointer has no effect either... So my question is, why is not permitted for __p to be a null pointer?


Solution

  • According to documentation for std::allocator::deallocate:

    Deallocates the storage referenced by the pointer p, which must be a pointer obtained by an earlier call to allocate(). The argument n must be equal to the first argument of the call to allocate() that originally produced p.

    Calls ::operator delete(void*), but it is unspecified when and how it is called.

    It seems to me that this specification allows an allocator to assume that the pointer is not null. The allocator you're looking at directly passes the pointer to ::operator delete(), but that may not be the case for all allocators.