2

I am reading about c++ allocators and the deallocate function has sentence that got my attention:

The argument n must be equal to the first argument of the call to allocate() that originally produced p; otherwise, the behavior is undefined.

Why is that? Why couldn't one deallocate part of the allocated memory, stupid example:

#include <memory>
#include <string>


int main()
{

    std::allocator<std::string> alloc;

    auto const p = alloc.allocate(20);

    alloc.deallocate(p+10, 10);

    return 0;
}
Mac
  • 3,397
  • 3
  • 33
  • 58
  • 2
    Not sure what sense you're asking "Why". Are you asking "Why doesn't this work today?" or are you asking "Why didn't the standard require allocators to support partial deallocation?" It doesn't work today because the standard says so. Why does the standard say so? Probably because the standard wanted to match existing practice. – Raymond Chen Apr 25 '16 at 21:11
  • If you did that the Memory Manager would lose track of which memory was protected ( and in use) and which wasn't. There is a linked list of structures holding position and size of each block of allocated memory, going to **p + 10** misses this info. – Arif Burhan Apr 25 '16 at 21:12

1 Answers1

2

Some allocators might be able to do that. The C++ specification only says what all implementations of the abstract allocator interface, Alloc<T>, are required to do. The committee decided not to require the feature you are asking about.

I don't have the C++ Rationale on this computer, but I suspect that the feature you are asking about is not required because the C memory allocator functions (malloc and free) cannot do it,1 and the C++ committee wanted it to be possible to implement the C++ library on top of the C library.

1 yes, realloc can do some cases of this, but not all of them

zwol
  • 135,547
  • 38
  • 252
  • 361
  • Being slightly pedantic, but realloc technically cant guarantee to do what is asked in any case, as realloc may move memory [_even if its made smaller_](http://stackoverflow.com/questions/1736433/can-realloc-move-pointer-if-new-size-smaller) – Mike Vine Apr 25 '16 at 21:58