Reputation: 111
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
Upvotes: 3
Views: 118
Reputation: 45484
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.
Upvotes: 7
Reputation: 14924
The code cannot change the content of the pointer p
in deallocater()
, thus it still shows the same value when printed. After the call p
still has the same (pointer) value, but the memory it points to is freed. This is known as a "dangling reference".
To update the pointer, use a double-pointer, or a reference to a pointer:
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;
}
Upvotes: 2