Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete heap allocated variable after function returns

I just wanted to know how one would go about, or if there is even a need to, delete [] an array declared like this:

int* arrgen(int x)
{
    int *newarray = new int[x];
    return newarray;
}

How would you go about deleting the newarray after the function returns? Or does it "auto" delete after the function returns along with the rest of the variable native to the function?

like image 720
D3r513g Avatar asked Aug 01 '26 12:08

D3r513g


1 Answers

No, you would have to delete from outside the function in this case. Anyway, if you deleted from inside the function, you would have a dangling pointer when returning, so it makes no sense.

If you want automatic deallocation, do this, making use of c++11:

std::unique_ptr<int []> newarray(new int[x]);
return newarray;

This will return newarray and when you stop using it, it will call delete [] through the unique_ptr destructor.

like image 118
Germán Diago Avatar answered Aug 04 '26 03:08

Germán Diago



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!