I was just a little confused why the same memory address was being printed when I attempted to delete a newly allocated variable through a function, I am guessing that no memory was leaked or pointer dangled.
The same memory address was printed.
#include <iostream>
using namespace std;
void deallocater(int *p)
{
delete p;
p = nullptr; // memory deleted and no dangling pointer right?
}
int main()
{
int *x = new int(1);
cout<<x;
deallocater(x);
cout<<endl<<x; // why is the same memory address being printed?
return 0;
}
I'm assuming that the function worked successfully
Calling the function
void deallocater(int* p)
{
delete p;
p = nullptr;
}
via
deallocater(x);
copies the value of x to p. Thus within deallocater() the local variable p is assigned nullptr. However, the variable x of the calling program is not altered.
You may achieve what you appear to want by taking the argument by reference:
void deallocater(int* &p)
{
delete p;
p = nullptr;
}
However, memory allocation and de-allocation should not be split apart into different and unrelated functions to avoid the danger of dangling pointers and/or memory leaks. Instead, good C++ code contains hardly any delete statements and few new statements (to initialize smart pointers), but instead use standard library constructs (containers and smart pointers) for memory management.
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