简体   繁体   中英

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

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?

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.

So long as the pointer has the same type and value 1 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[] .


1 Qualifiers ( const , volatile ) don't matter. Note that you can also use a pointer to a base class with a virtual destructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM