If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Re: Resource leak.. ?

Originally Posted by hemant.bhargava7

Want to know what is the best way to avoid this leak?

It depends on what you mean by "best way". The program you posted is too trivial to tell you what is best or better. To recommend the "best way" requires us to see the real program you're working on and have you describe the issues you're having when it comes to memory allocation/deallocation.

However in general, you should attempt to avoid writing code where one function allocates, and another function (or the user of the function) has to remember to deallocate.

1) What if the allocation scheme changes in func_b()? Then all modules calling func_b() need to change to deallocate properly. This means more maintenance and a possibility of incorrect/mismatch allocation and deallocation methods being called.

2) And just in general, what if the client/user of func_b() just forgets to call "delete" (or the deallocation function)? A memory leak.

Writing code like this puts your code more at risk for memory leaks and/or wrong usage. Things such as smart pointers, RAII, etc. reduces the need to use "new" in such a wide-open fashion as what you've posted.

Re: Resource leak.. ?

Is this optimal solution? I would be great if someone can suggest alternative way.

The best alternative is to use reference counting smart pointers. There's one called std::shared_ptr which is part of the language (since C++ 11).

It's used like an ordinary pointer but makes sure the allocated object is deleted automagically when it's not referenced from anywhere anymore. The only principal drawback is that it cannot handle circular references (like for example a circular linked list).

Another alternative is to use a third-party garbage collector but that's advanced and not very common in C++. The only one you ever hear about really is the Boehm GC. Hopefully the situation will improve now that C++ in under increasing pressure from GC based languages.

* The Perfect Platform for Game Developers: Android
Developing rich, high performance Android games from the ground up is a daunting task. Intel has provided Android developers with a number of tools that can be leveraged by Android game developers.

* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.