Can I delete a memory previously allocated dynamically, but with a different pointer?

纵然是瞬间 提交于 2021-02-08 07:22:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!