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!!
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!!
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
}
"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.
You should start from the bottom, and go up. Otherwise, you will lose your reference to the data reference down the chain of references!
1. Delete the data you get by dereferencing twice, i.e. *myPtrToPtr
2. Delete the data you get (the pointer) by dereferencing once, i.e. myPtrToPtr
But of course, only do this if both the pointer and the thing it is pointing too have been dynamically allocated.
By I agree with the commenter... being more specific would be helpful to give us some context.
You first need to define who is the owner of each pointer before thinking about destroying it.
And if you have to destroy a pointer which points to a pointer you own, then you need to either destroy the referenced pointer first or save its value temporarily before destroying the other one.
But you should consider using a memory checking tool like valgrind/purify or equivalent and think about who is owning what (ie : who should destroy who) before doing wild guess.