Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a pointer before return it in a function?

Tags:

c++

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?

like image 619
Jarkid Avatar asked Oct 12 '25 19:10

Jarkid


2 Answers

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;
like image 123
acraig5075 Avatar answered Oct 14 '25 08:10

acraig5075


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.

like image 36
Yousaf Avatar answered Oct 14 '25 07:10

Yousaf