Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delete pointer that is assigned from another pointer, should i delete the other one again?

Tags:

c++

pointers

so, here is my example to explain this question

void * p1;
int * p2, * p3;

p2 = new int;
p1 = p2;
p3 = (int *) p1;

to free the memory, are the following 3 lines equivalent to each other?

delete p2;
delete p3;
delete (int *) p1;

the reason i am using such is that i want to pass a pointer between functions without knowing its type, for instance i define a void pointer and changes its value by calling other functions as follow:

void * p1;
func1(p1); //in this function, p2 = new int and  p1 is assigned as p1 = p2;
func2(p1); //in this function, p1 is assigned to another pointer: int * p3 = (int *)p1;

then, i called func3 to release the memory

func3(p1); //delete int * p1

after calling func3, do i have to deal with p2 in func1 anymore?

thanks!

like image 597
shelper Avatar asked Dec 02 '22 21:12

shelper


2 Answers

Yes, all 3 deletes are equivalent. It's important to note that in the posted example, all 3 pointers point to the same thing. This means if you delete one of them, you should not delete the others as the memory they point to has already been released.

If you do try to delete something that has already been released, you'll evoke Undefined Behavior. If you're lucky your program will crash, but anything could happen.

like image 160
John Dibling Avatar answered Dec 16 '22 02:12

John Dibling


The question contains a misconception: you don't delete the pointers. You delete what they point to.

And you cannot delete a same thing more than once.

Think to three people pointing their fingers towards a same box. One of them says "throw it away". Once it has been thrown, they will remain with their finger still pointing in the same direction towards an empty space. With nothing more to throw away.

like image 36
Emilio Garavaglia Avatar answered Dec 16 '22 03:12

Emilio Garavaglia