If we have a function like this:
int* foo()
{
int *x;
x = new int;
delete x;
return x;
}
We need to return a pointer in a function, but what we have learned is we need to delete a space in the final.
If we delete x
first as above, then is it meaningful to return x
in the final line? Because the x
does not exist anymore.
But if we don't delete x
before return, the function will be finished.
How can we do? Or we don't really need to delete a space which was allocated in the memory?
You do need to delete
the pointer at some stage, but that does not have to be in the same function scope where you new
it. It can happen outside of your function, which I think is what you're trying to achieve.
int* foo()
{
int *x;
x = new int;
return x;
}
int *px = foo();
// use px in some way
delete px;
if we delete x first as above, then is it meaningful to return x in the final line? because the x does not exist anymore.
Two things here, first no it is not meaningful to return x
after delete x;
and secondly, deleting x
won't delete the x
itself, it will only free up the memory to which the x
points to.
or we don't really need to delete a space which was allocated in the memory?
Wrong. You need to free up every dynamically allocated memory location.
but if we don't delete x before return, the function will be finished. how can we do ?
What you can do is declare the pointer outside the function and then after you have returned the pointer x
from the function, then you can delete it anywhere outside that function which returned the pointer.
Tip:
Consider using Smart Pointers because along with other benefits, one of the biggest benefit of using Smart Pointers
is that they free up the allocated memory automatically and save you the headache of freeing up the memory explicitly.
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