C ++ default allocator - what should happen if the size is not equal to the size passed to the allocation call?

20.6.9:

void deallocate(pointer p, size_type n); 
  • Required: p must be a pointer value obtained from allocate (). n must equal the value passed as the first argument to the allocate call that p returned.
  • Effects: frees the repository referenced by p.
  • Notes: Uses :: operator delete (void *) (18.6.1), but it is not specified when this function is called.

What should happen if n does not match the value passed as the first argument to the allocate call that p returned? Do not free? Throw std::bad_alloc ? ...

EDIT: What I actually meant with โ€œwhat should happenโ€ was: could it be thrown away or approved in a user implementation?

+6
source share
3 answers

As usual in C ++ Standard, when nothing is specified explicitly, violation of the requirements leads to undefined behavior. It should always be a requirement, not an option in the C ++ standard.

For example, here MSDN says :

The _Ptr pointer must be previously returned by a call to highlight for the allocator object, which is compared to * this, highlighting an array object of the same size and type.

which means that the size must match exactly, otherwise you will encounter undefined behavior.

+10
source

He does not speak. This means that it would be an unpleasant "undefined behavior".

+3
source

This is present in the standard, which allows the use of basic allocators that do not know the size of the allocation from its pointer.

For example, the AmigaOS allocator maintains a list of free memory blocks and even allows partial deallocation (i.e. if I allocate 1024 bytes and then release 512 bytes at offset 256, I get two 256 byte allocations), so the allocator expects me to transfer this information to the liberator.

+1
source

Source: https://habr.com/ru/post/893234/


All Articles