Wednesday, October 17, 2012

What are Memory Leaks?


A memory leak, in computer science (or leakage, in this context), occurs when a computer program consumes memory but is unable to release it back to the operating system.

When a program needs to store some temporary information during execution, it can dynamically request a chunk of memory from the system. However, the system has a fixed amount of total memory available. If one application uses up all of the system’s free memory, then other applications will not be able to obtain the memory that they require. The implications of a “memory starved” application can range from a graceful shutdown to an unexpected crash. Most large scale applications regularly request memory, so running out of system memory tends to have a domino effect. Even if the applications do not terminate, the system will slow down to a crawl—or even hang—in low memory conditions. Clearly, none of these results are desirable, so the system never wants to run out—or run low—of memory.

It is the responsibility of each application to “free” dynamically requested memory when they are finished using it. Freeing the memory returns it to the system, where it can be re–allocated to another application when needed. When an application dynamically allocates memory, and does not free that memory when it is finished using it, that program has a memory leak. The memory is not being used by the application anymore, but it cannot be used by the system or any other program either.

Memory leaks add up over time, and if they are not cleaned up, the system eventually runs out of memory. Most everyone has seen the “Your computer is running low of virtual memory” message box on Windows when memory gets too high. It is typically accompanied by horribly slow response time, and often the user can’t even close the wasteful application because of this sluggishness. The only response at that point is to reboot the computer.

Linux: Check For Memory Leaks In Programs

Valgrind :It is memory debugging, memory leak detection, and profiling tool for Linux and Mac OS X operating systems. Valgrind is a flexible program for debugging and profiling Linux executable.
 

How Do I Install Valgrind?

Type the following command under CentOS / Redhat / RHEL Linux:
# yum install valgrind
Type the following command under Debian / Ubuntu Linux:
# apt-get install valgrind

How Do I use Valgrind?

If you normally run your program like this:
./a.out arg1 arg2
OR
/path/to/myapp arg1 arg2
Use this command line to turn on the detailed memory leak detector:
valgrind --leak-check=yes ./a.out arg1 arg2
valgrind --leak-check=yes /path/to/myapp arg1 arg2

You can also set logfile:
valgrind --log-file=output.file --leak-check=yes --tool=memcheck ./a.out arg1 arg2
Most error messages look like the following:
cat output.file

No comments:

Post a Comment