dimanche 27 mai 2018

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

I'm new in C++ and I've a problem with memory management.

I've one method a() that call 3 method (b(),c(),d()) that, each one return dinamically 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 operation in a() I must delete the 3 arrays that I created with the 3 methods. If I do the 3 delete like code in the top of question is it ok?

I asked myself this question because I think that this code correctly delete all but analyzing the memory allocation of my c++ program I can't notify this delete.

Aucun commentaire:

Enregistrer un commentaire