C++ Logo

std-discussion

Advanced search

Re: Size of heap allocated array

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 14 Apr 2026 10:37:01 -0400
On Tue, Apr 14, 2026 at 10:24 AM Marcin Jaczewski
<marcinjaczewski86_at_[hidden]> wrote:
>
> wt., 14 kwi 2026 o 16:08 Jason McKesson via Std-Discussion
> <std-discussion_at_[hidden]> napisał(a):
> >
> > On Tue, Apr 14, 2026 at 5:42 AM Marcin Jaczewski via Std-Discussion
> > <std-discussion_at_[hidden]> wrote:
> > >
> > > wt., 14 kwi 2026 o 11:04 Yongwei Wu <wuyongwei_at_[hidden]> napisał(a):
> > > >
> > > > I think it can work on pointers to (an array of) non-trivially-destructible objects. Maybe nobody finds a real usage scenario for this, thus no one has proposed it?
> > > >
> > >
> > > Real usage for me of this feature would be reduce size of
> > > `std::vector` as in this case you could avoid `capacity` duplication
> > > in vector.
> > > Of corse this will work only if allocator used `new[]` instead other
> > > manual handling, but even in this case allocator should perhaps know
> > > how big array is?
> >
> > But the allocator's allocation and deletion functions explicitly take
> > a size. So the allocator explicitly does not need to know the size;
> > you have to provide it. And some allocators flat-out *cannot* know the
> > size; they just don't track that because the caller is supposed to.
>
> Ok, I missed this part, but updating my knowledge from
> cppreference.com I notice this:
>
> """
> The argument n must be equal to the first argument of the call to
> allocate() that originally produced p,
> or in the range [m, count] if p is obtained from a call to
> allocate_at_least(m) which returned {p, count}
> """
>
> This "or" cause is concerning as you can give any value in that range
> and if value is critical then
> allocator needs to know what exactly was returned from `allocate_at_least`.
> Or does this assume "bucket" allocation where only approximated size
> is enough to recover proper value?

An allocator which supports `allocate_at_least` (which is not required
to be supported by every allocator) is one that probably does not
really need to know the array count to deallocate the memory. I'm
fairly sure the idea behind `allocate_at_least` is to allow for
containers like `vector` to know the true size of the allocation and
thus be able to use that extra size for their capacity.

Received on 2026-04-14 14:37:16