Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ default allocator - what should happen if the size doesn't equal the size passed to the invocation of allocate?

Tags:

c++

std

allocator

20.6.9:

void deallocate(pointer p, size_type n);
  • Requires: p shall be a pointer value obtained from allocate(). n shall equal the value passed as the first argument to the invocation of allocate which returned p.
  • Effects: Deallocates the storage referenced by p.
  • Remarks: Uses ::operator delete(void*) (18.6.1), but it is unspecified when this function is called.

What should happen if ndoesn't equal the value passed as the first agrgument to the invocation of allocate which returned p? Not deallocate? Throw std::bad_alloc? ...

EDIT: What I actually meant with "what should happen" was: Would it be okay to throw or assert in a custom implementation?

like image 630
0xbadf00d Avatar asked Jul 21 '11 06:07

0xbadf00d


2 Answers

As usual in C++ Standard, when nothing is stated explicitly, violating the requirements leads to undefined behavior. Shall means at all times must, it's a requirement, not an option in C++ Standard.

For example here's what MSDN says:

The pointer _Ptr must have been returned earlier by a call to allocate for an allocator object that compares equal to *this, allocating an array object of the same size and type.

which means that the size must match precisely, otherwise you run into undefined behavior.

like image 115
sharptooth Avatar answered Oct 10 '22 15:10

sharptooth


It doesn't say. Which means that it would be the nasty "undefined behviour".

like image 24
Bo Persson Avatar answered Oct 10 '22 14:10

Bo Persson