Resource leak..

1
2
3
4
5
6
7
8
9
10
11
#include<iostream>

int* func_b() {
  int *c = new int;
  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 = new int;
  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.
Last edited on
http://en.cppreference.com/w/cpp/memory/unique_ptr

have a google of "RAII" as well.
Last edited on
It is a solution.

I would probably use smart pointers:
http://en.wikipedia.org/wiki/Smart_pointer#C.2B.2B_smart_pointers
Yes. Smart pointer seems to be optimal solutions to avoid these kind of leaks.

Thanks.
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.
Topic archived. No new replies allowed.