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;
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;
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.