Memory Leak & Dangling Pointer in C

Memory Leak & Dangling Pointer


Memory leak and dangling pointer are the two common problems that programmers face. These problems are generally observed in large projects where thousands of lines of code is involved and there are hundreds of instances where the programmers would need to access different memory locations. Let's know what each of these two are:

Memory Leak:

In a program a memory leak is said to have occurred if a dynamically allotted memory is not deleted or freed and there is no way the program can again access to the same memory location. Lets look at an example to clearly understand how memory leak occurs.

#include <iostream>
using namespace std;

int* fun()
{
int *p = new int;
*p = 50;
return p;
}

int main()
{
int *q = fun();
cout<< *q<< endl;
return 0;
}

If we observe in the above code, in the function fun(), for pointer 'p' memory has been dynamically allocated and it is the responsibility of the programmer to free/delete the allocated memory. After fun() has returned there is no way for the programmer to access 'p' again as it is local to fun(). So the term "Memory Leak" makes sense here because the allotted memory is not deleted. Now let's look into what Dangling pointer is and how it is different from Memory Leak.


Dangling Pointer:

Dangling pointer is a situation which occurs when a programmer tries to access a memory location through the variable/pointer when the memory is already freed. Suppose if a programmer allocates a memory and store its address in a pointer. If the memory allotted is freed and if the programmer continues to refer to that memory location through the pointer then it is a case of dangling pointer. Generally this situation will lead to run time error or "Segmentation Fault". Lets look at one example before we conclude this article.

#include <iostream>
using namespace std;

int *p;

void fun()
{
p = new int;
*p = 50;
}

int main()
{
fun();
int *q = p;
cout<< *q<< endl;
delete p;
*q = 100;
cout<< *q<< endl;
return 0;
}

In the above example, if we observe both the pointers 'p' & 'q' are pointing to the same location. Now even after 'p' has been deleted, the programmer tries to access the same memory location assuming that still 'q' exists. But when the memory is already freed, how is it possible to refer to the same memory location. 

Share on Google Plus

About Kapil Thakar

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment

Related Posts Plugin for WordPress, Blogger...