vendredi 12 février 2021

Declaring a pointer inside a function, C++

What happens when I register a new pointer inside a function? I acknowledge, that the pointer's name should be destroyed. But what happens to the memory allocated? Will it be a memory leak? In my example, does the data object stay valid after the function is terminated, or it works just by chance, being prone to undefined behavior in more complicated instances? Where should be correct to place delete in this example? Or should this way of writing be avoided?

int * one (void);

int main (void){
    int *two = new int;
    *two = *one ();
    cout << "Address: " << one() << "|" << *one() << endl; // Address: 0xe51a78|5555
    cout << "Address: " << two << "|" << *two << endl;  // Address: 0xe519d8|5555
}

int * one (void){
    int * pFun = new int; // declaration of a pointer inside a function
    *pFun = 5555;
    return pFun;
}

Aucun commentaire:

Enregistrer un commentaire