Brijgopal Bharadwaj
Brijgopal Bharadwaj

Reputation: 23

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?

Upvotes: 1

Views: 492

Answers (2)

Bathsheba
Bathsheba

Reputation: 234795

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[].


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

Upvotes: 1

Ron
Ron

Reputation: 15521

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.

Upvotes: 5

Related Questions