Hi
What is meant by memory leak and how can we prevent it.
Thanks in advance
Sudhakar.M
Printable View
Hi
What is meant by memory leak and how can we prevent it.
Thanks in advance
Sudhakar.M
In short, a memory leak is experienced when a program allocates a block of memory and never frees it to the operating system.
A good way to prevent memory leaks is to avoid new/delete (or malloc/free) when writing C++ programs. Instead, use containers like std::vector, std::list, or std::map. Also, instead of using char * arrays to represent strings, use std::string.
Just an added note, it will be most obvious if you're allocating large blocks of data, or if you are allocating data in a loop and not freeing it. If you can't avoid new/delete, you can try using smart pointers. They have a couple of oddities, but they are very useful. Check it out here
http://ootips.org/yonat/4dev/smart-pointers.html
They have the added benefit of cleaning themselves up when they go out of scope. Good luck.
~Steve
Normally, you can throw exception to tell you that the memory is leaking!
The best way to know about a memory leak is overloading new and delete operators. In the new routine keep account of how much memory you have allocated and in delete routine keep account of memory that has been freed. So at the end you can flash a message showing the difference of total allocated and de-allocated memory. The difference is the MEMORY LEAK. It will show you how much bytes of memory is leaking. But it works with C++ only, not with C.
All the Best.
See also the FAQ about memory leaks.