0

In C++, we dynamically allocate the memory with the new operator. My question is that after we modify the returned pointer, can the delete operator know where to start to delete? such as:

int (*a)[5] = new int[1][5];
a=a+1;
delete[] a;
Kicr
  • 145
  • 1
  • 12

1 Answers1

0

No. Dynamically allocated memory can only be deallocated using the pointer returned from the allocation.

This is the case because in practice, the allocator is storing allocation metadata before the pointer it returns (so it knows how to free it appropriately). If you pass it a pointer to later in the allocation, it will try to read the preceding bytes as the allocation metadata, but of course it's not allocator metadata, it's whatever random data you put there.

There are other allocation strategies that might avoid placing the allocation metadata there (bit fields and the like), but those cases are less common, and still generally not able to handle arbitrary freeing of memory not aligned to the allocation's expected alignment.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • Thanks! Is there some reference to this allocation metadata? – Kicr Feb 14 '18 at 02:46
  • @RickyZhou: It's allocator/runtime dependent. It's not something you can or should mess with (it's not part of the language standard at all, can change at any time, etc.). Trying to do so is how you end up with programs that break on the next release of the OS (or even just on upgrades to the C/C++ runtime). – ShadowRanger Feb 14 '18 at 02:49