-->

Memory leak

Posted by Admin on
What is memory leak ?

In computer science, a memory leak occurs when a computer program incorrectly manages memory allocations. When Dynamically allocated memory is not freed after its use, it leads to memory leak. In object-oriented programming, a memory leak may happen when an object is stored in memory but cannot be accessed by the running code.

See the following examples :

Example in C:

char *memoryArea = malloc(10);
char *newArea = malloc(10);

this will assign the memory as follows:


memoryArea and newArea have been allocated 10 bytes each and their respective contents are shown in Figure above.

If somebody executes the following statement 


memoryArea= newArea

then memoryArea which wass earlier pointing to the MEMORYAREA now will point to the ITSNEWAREA . Hence MEMORY AREA will become orphan .



From the above figure we can easily see that no reference is pointing to the MEMORYAREA .Hence it can't be freed as nothing is pointing to this memory area using which we could free it .So will memory be preserved and wasted which will lead to memory leak.    

Example in C++


int main() {
    // OK
    int * p = new int;
    delete p; 

    // Memory leak
    int * q = new int;
    // no delete
}
As in above example we can see that we have not deleted the q after creating it hence it will lead to memory leak.

In Java memory leaks does not happen so easily because Java manage the Garbage collection automatically. This is one of the important strength of Java.







No comments:

Post a Comment