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.