Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a pointer to a pointer?

Tags:

c++

In C++, if you pass a pointer to a pointer into a method, do you delete the referenced pointer first? Do you have to clean it up within the method? I'm checking memory in task manager and it is leaking!

Thanks!!

like image 992
Moderator71 Avatar asked Dec 28 '22 06:12

Moderator71


2 Answers

You delete a pointer to a pointer like this:

int** p = 0;
p = new int*;  // create first pointee 
*p = new int;  // create 2nd pointee
**p = 0;       // assign 2nd pointee
// free everything
delete *p;     
delete p;

It seems unusual to me to delete a pointer that was passed into a method. But anyways:

void freeme(int **p) {
    delete *p;
    *p = 0;
}

int main() {
    int *a = new int;
    *a = 3; 
    freeme(&a);
    // a == 0 now
}
like image 127
WolfgangP Avatar answered Dec 30 '22 20:12

WolfgangP


"A pointer to a pointer" ?

If for exemple you have :

MyClass * obj_ptr = new Myclass();
MyClass ** obj_ptr_ptr = &obj_ptr;

//then if you want to clean do :

delete (*obj_ptr_ptr);//to clean the class instance.

Why would you need to clean the pointer ... if you used malloc ... or any other dynamic (heap) allocation only. But It's probably on the stack that you allocated the pointer so you don't need to clean it. At the end of his scope the memory on the stack used in the scope is cleaned.

like image 28
dzada Avatar answered Dec 30 '22 20:12

dzada