#include<iostream>
int* func_b() {
int *c = newint;
return c;
}
int main() {
int* b = func_b();
return 0;
}
I can see that memory leak would be there in above code because I am not freeing the memory allocated using "new".
Want to know what is the best way to avoid this leak? One solution is:
1 2 3 4 5 6 7 8 9 10
int* func_b() {
int *c = newint;
return c;
}
int main() {
int* b = func_b();
delete b;
return 0;
}
Is this optimal solution? I would be great if someone can suggest alternative way.
Also FWIW, there is no need for dynamic allocation in this example. func_b could just as easily return an int by value and avoid the confusion of memory management altogether.
Although I suppose this is a trivial example for a more complex problem. If func_b was a factory that returned an abstract pointer, for example... then that would make sense (and yes, in that case I'd use a smart pointer).
Though in general... don't use dynamic allocation unless you have to.