Is taking a pointer to the interior of a contiguously-laid-out array, then shortening the length of the array and dereferencing that now-dangling pointer, a spatial or temporal memory safety violation? Seems to me that the distinction gets very blurred in this case.
Conversation
Growing and shrinking are semantically very similar operations. They're nearly the same thing for all commonly used sizes with modern allocators. They round to a size class and if the size class is smaller or larger than before it has to be moved to a new allocation elsewhere.
1
Expecting shrinking not to reallocate is a misconception not aligned with how modern allocators work. For example after an initial 4 special cases for 16, 32, 48 and 64, jemalloc has 4 size classes per doubling of size. 897 byte alloc rounds to 1024. Shrink to 896 and it's moved.
2
Again, depends on your definition of "shrink". Some array shrink operations (e.g. C++ std::vector::resize) are guaranteed not to involve the allocator.
1
std::vector supports a shrink_to_fit method. Length and capacity are separate things for a dynamic array and we're talking about capacity here.
Patrick's initial problem description seems to fit the length-not-capacity case equally well. He's not using technically precise language. Seems fine to map "shorten" == std::vector:resize and "dangling pointer" == invalidated iterator.
1


