Click to See Complete Forum and Search --> : Memory Leak


sudhakarm
December 8th, 2004, 11:11 AM
Hi

What is meant by memory leak and how can we prevent it.

Thanks in advance
Sudhakar.M

Bob Davis
December 8th, 2004, 11:16 AM
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.

diehardii
December 8th, 2004, 11:44 AM
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

walkinginwater
December 8th, 2004, 11:59 AM
Normally, you can throw exception to tell you that the memory is leaking!

Andreas Masur
December 8th, 2004, 04:56 PM
For Windows:

Detecting and Isolating Memory Leaks (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsdebug/html/vxcondetectingisolatingmemoryleaks.asp)
Detecting Memory Leaks in MFC (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vsdebug/html/_core_detecting_memory_leaks.asp)

mukeshvijay79@hotmail.com
December 8th, 2004, 10:51 PM
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.

cilu
December 9th, 2004, 02:48 AM
See also the FAQ about memory leaks.