2

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
JustinBlaber
  • 4,629
  • 2
  • 36
  • 57
  • 1
    There's been some change in C++11 related to calling `delete` on NULL pointers. See [my question](http://stackoverflow.com/questions/25329576/calling-delete-on-null-pointers-c03-vs-c11) on the subject. – R Sahu Jan 07 '15 at 22:07
  • 1
    A deallocator can't be asked to deallocate memory that it didn't allocate itself. A custom allocator that never returns NULL on allocation should be able to assume that it's never asked to deallocate NULL. – molbdnilo Jan 07 '15 at 22:17

1 Answers1

4

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.

Community
  • 1
  • 1
Greg Hewgill
  • 951,095
  • 183
  • 1,149
  • 1,285