Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible memory leak when returning pointer (array) (C++)

Consider the code snippet in C++:

int *foo() {
    int *y = new int[1000];
    return y;
}

int main() {
    int *x = new int [1000];
    x = foo();
    delete[] x;
    return 0;
}

When x is created it points to a memory address. When foo() is called, a new pointer y is created, pointing to a different address, but x is then set to the address that y had. So when it is deleted, the new address's memory is freed, but the original address that x had is leaked. Is that correct?

Furthermore, I made a slight change to the snippet by calling delete[] x before calling foo() and it still compiled and ran:

int *foo() {
    int *y = new int[1000];
    return y;
}

int main() {
    int *x = new int [1000];
    delete[] x;
    x = foo();
    delete[] x;
    return 0;
}

Does this mean I prevented the leak? And one final question, if I do not initialize x when I declare it, but do not prematurely delete it, is it pointing to memory that will be leaked? Like below:

int *foo() {
    int *y = new int[1000];
    return y;
}

int main() {
    int *x;
    x = foo();
    delete[] x;
    return 0;
}

As a side note, I understand that using a vector and/or unique pointers is safer, but I'm curious as to the functionality of the code above, specifically what happens when a pointer is declared but initialized later.

like image 871
Daniel Avatar asked Oct 23 '25 13:10

Daniel


1 Answers

When x is created it points to a memory address. When foo() is called, a new pointer y is created, pointing to a different address, but x is then set to the address that y had. So when it is deleted, the new address's memory is freed, but the original address that x had is leaked. Is that correct?

Yes.

Does this mean I prevented the leak?

Yes.

And one final question, if I do not initialize x when I declare it, but do not prematurely delete it, is it pointing to memory that will be leaked?

No.

As a side note, I understand that using a vector and/or unique pointers is safer

Absolutely. Even without those your code could be a lot clearer about memory ownership such that your question wouldn't even arise, but it's true that switching to standard containers/smart pointers would solve the problem right at the source, and I strongly recommend this.


tl;dr: you're right about everything so far

like image 169
Lightness Races in Orbit Avatar answered Oct 25 '25 03:10

Lightness Races in Orbit