Reputation: 14448
This looks simple question but my friend debated with me that below program invokes UB. But I think he is incorrect. Consider following program:
#include <iostream>
int main()
{
int* p=new int[3]();
int* q=p;
for(int i=0;i<3;i++)
std::cout<<q[i]<<' ';
delete[] q;
std::cout<<'\n';
}
Is this program's behavior well defined? What happen if I write delete[] p; instead of delete[] q; ? Is it valid?
Upvotes: 1
Views: 131
Reputation: 10618
The pointer returned by the new[]
operator is not the start of the allocated memory but rather points to the first object (or the object at index 0). Now, based on the compiler you're using, the run-time system stores the number of objects, n, somewhere where it can be retrieved if you only know the memory location pointed by p
.
According to this blog, the deletion of a vector performs this operation in reverse:
When you do "delete[] p", you are saying, "p points to a bunch of objects, but I'm not telling you how many." In this case, the compiler needs to generate extra code to keep track of how many it needs to destruct. This extra information is kept in a "secret place" when the vector is allocated with "new[]".
Since doing int *q = p
essentially points to the same array's 0th object, it is equivalent to call delete[] q
and delete[] p
.
Upvotes: 2
Reputation: 6407
Operator delete
can be applied ONLY to memory (i.e. address) that was allocated with operator new
. If you allocate once you should free (detele) also once, does not metter which pointer (variable storing address) is used, so your code is valid.
But, remember, after you delete[] q
neither q
nor p
DO NOT have to be used. The best way is assigne NULL
to both pointers.
Upvotes: 1
Reputation: 181047
Yes the program is well defined. First you create a pointer assigned to newly allocated memory.
int* p=new int[3]();
Then you create another pointer pointing to that memory
int* q=p;
You then use that pointer to assign data into that memory. After that you delete memory which is pointer to q
which is the same as p
which is okay. The program returns and all is well
delete
doesn't care about what variable you use. What is important is that the memory that the pointer points to was created with new
and that you only call delete once on the memory.
Upvotes: 5