问题
I was making a program for linked list in C++. To implement the concept, I created a pointer 'start' globally, pointing to the first element of the list.
After completion of the program I tried to delete all memory allocated dynamically to prevent memory leaks, by accessing successive nodes using the start and another locally declared pointer 'p'. Here, I used a pointer pointing to the same correct addresses, but this pointer was not the one used for memory allocation, but was declared locally like any normal pointer.
My question is - Is it possible to delete the dynamically allocated memory by using the normal pointers pointing to the same location?
回答1:
Yes you can. This is valid:
int* p = new int;
int* q = p;
delete q;
The equivalent when using new[]:
int* p = new int[123];
int* q = p;
delete[] q;
Substitute int*
with your pointer type. Whether to set the pointers to nullptr
afterwards is up for debate.
回答2:
So long as the pointer has the same type and value1 as the one you got back from new
, yes you can use that as the delete
argument.
Also, remember to use delete[]
if you used new[]
.
1Qualifiers (const
, volatile
) don't matter. Note that you can also use a pointer to a base class with a virtual destructor.
来源:https://stackoverflow.com/questions/47771734/can-i-delete-a-memory-previously-allocated-dynamically-but-with-a-different-poi