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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With