Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return dynamically allocated array from function and correctly delete it

I'm new to C++ and I have a problem with memory management.

I have one function a() that calls 3 functions (b(), c(), d()), each one of which returns a dynamically allocated array of MyClass objects:

void a(){
    MyClass * one=b();
    MyClass * two=c();
    MyClass * three=d();
    //operate with 3 array (one, two and three)
    delete [] one;
    delete [] two;
    delete [] three;
}

MyClass * b(){
    MyClass * array=new MyClass[2000];
    //many operations on array
    return array;
}

MyClass * c(){
    MyClass * array=new MyClass[2000];
    //many operations on array
    return array;
}

MyClass * d(){
    MyClass * array=new MyClass[2000];
    //many operations on array
    return array;
}

After many operations in a() I must delete the 3 arrays that I created with the 3 functions. If I do it using the 3 delete [] expressions like those in the code above, is it ok?

I asked myself this question because I think that this code deallocates everything correctly, but analyzing the memory allocation of my c++ program I see no evidence of this deletion.

like image 773
Antonio1996 Avatar asked Mar 08 '26 14:03

Antonio1996


1 Answers

For reliable memory-management you should use smart pointers such as std::unique_ptr. So when your function is returning a dynamically allocated value it should instead return std::unique_ptr to that value to make sure that this value will be deallocated.

std::unique_ptr<MyClass[]> array(new MyClass[2000]);

In your case however you should consider using std::vector instead of raw array.

like image 113
r3mus n0x Avatar answered Mar 10 '26 02:03

r3mus n0x



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!