Difference between dangling pointer and memory leak

dangling pointer and memory leak

There are a lot of people who asked me the difference between dangling pointer and memory leak. I have found that some people understand both are the same things.

In this article, I will not only discuss the basic difference between dangling pointer and memory leak but also discuss some important points that help you to prevent the memory leak.

Basically, dangling pointer and memory leak are the different terms. If a pointer is pointing to memory that is not owned by your program (except the null pointer ) or an invalid memory, the pointer is called a dangling pointer. Generally, daggling pointers arise when the referencing object is deleted or deallocated, without changing the value of the pointers.

In opposite of the dangling pointer, a memory leak occurs when you forget to deallocate the allocated memory. In C language compiler does not deallocate the memory automatically it is freed by the programmer explicitly. In another word, you can say that memory leak is a type of resource leak.

Note: once you allocate a memory than allocated memory does not allocate to another program or process until it gets free.

Let’s see the dangling pointer and memory leak in depth to understand the difference between dangling pointer and memory leak.

Dangling pointer

In the program, we should not use the dangling pointer. It can be the cause of memory faults. Here I am mentioning few forms of the dangling pointer, I think you should know.

1. If a pointer points to an address that not belongs to your process but knows by the OS, then this type of pointer is dangling pointer. You should not use such type of pointers is because it leads to a memory fault.

2. Static and automated memory is handled by the compiler but if you allocate the memory in heap memory, the developer needs to free the allocated heap memory. The deleted pointer is another type of dangling pointer is because you have freed the memory but still its pointing to that memory.

For example,

 

After the deallocating the memory, p becomes the dangling pointer and if you try to access the p, your program could be crash.

3. An uninitialized pointer is called dangling pointer (also called wild pointer) because we don’t know where it points. So we should always initialize the pointer. It is prevented from the undesired result.

int* p; //uninitialized pointer

*p = 10; // Show undefined behaviour

4. The stack frame that is allocated to a function is destroyed after returning the control from the function. The common mistake performed by the developer is that to return the address of the stack allocated variable from the function. If you tried to access the returning address from the pointer, you will get the unpredictable result or might get the same value but it is very dangerous and need to avoid.

Example,

In below code, Data has not scope beyond the function. If you try to read the value of Data after calling the Fun() using the pointer may you will get the correct value (5), but any functions called thereafter will overwrite the stack storage allocated for Data with other values and the pointer would no longer work correctly.

So in the below code piData is a dangling pointer that is pointing to a memory which is not available.

 

5. If you try to access the array outside of the array boundary, it also considers dangling pointer because shoe the undesired behavior.

For example,

int arr[5];
arr[8] = 10;

In above example, allowed indices of the array (arr) are 0 to 4, and arr[8] is outside the array. (show undefined behavior).

If you love online courses, then here is a good c language course for you from the Pluralsight, 10 days trial is Free.

C tutorial

Memory Leak

Memory leak is a curse for because software, due to the memory leak software shows undefined behavior. I have already discussed at the beginning of the article that in c language dynamically allocated memory does not deallocate itself, programmer responsibility to deallocate it.

If in the application, programmer forgets to deallocate the memory, then it creates the problem because this memory is not released. This not released memory is not used by the process again, so problems come in the scenario when the process has a lot of memory but still not able to use it. Generally, this type of problem creates the issue when application or software run continuously.

Let’s see a program,

In below program, programmer forgets to free the allocated memory, it can cause a memory leak.

 

How to avoid creation of the dangling pointer in C?

We can easily prevent the creation of dangling pointer to assign a NULL to the freed pointer. The behavior of NULL pointer is defined, if you tried to dereference the NULL pointer, then memory fault occurs.

See below example,

Another way to avoid creation of the dangling pointer is that to avoid return the address of local variable and array from a function. It is a very common mistake that is not cared by the fresher.

Using the dynamic memory allocation or static variable or array, we can resolve the above problem.

See the example code,

Grammarly Writing Support

How to avoid memory leaks in C?

We can avoid the memory leak to perform the following tricks.

Create a counter to monitor allocated memory

It is a good technique to prevent the memory leaks. In this technique, we will create two global counters and initialize them with 0. In every successful allocation, we will increment the value of the counter1 (Allocate_Counter ) and after the deallocating the memory we will increment the counter2 (Deallocate_Counter). At the end of the application, the value of both counters should be equal.

This method helps you to track the status of allocated memory. To implement this technique we need to create three customize function, one for memory allocation and second for memory deallocation and last one to check the memory leak.

 

Every malloc or calloc should have a free function

It is a golden rule to write the free function after each malloc (calloc). Suppose in an application you have required to create an array of character to store some dynamic data. You have to use memory management function (malloc or calloc) to allocate the memory. After writing the expression of malloc its good habits to write the free function corresponding to the allocating memory.

char *pInfoData = malloc(n *sizeof(char));
free(pInfoData);

Now start to write the code between malloc and free function.

char *pInfoData = malloc (n *sizeof(char));

//Do some work

free(pInfoData);

Sometimes we have required allocated memory throughout the application, in that situation we have to write the free function after just writing the malloc in the handler that will invoke at the ending of the application.

For example,

Suppose there is a callback function DeactivateHandler() that is invoked at the end of the application, so we have to write the free function in DeactivateHandler() just after writing the malloc. These techniques reduce the probability to forget to free the memory.

Do not work on the original pointer

It is a good habit to work on a copy of the pointer, it preserves the address of allocating memory. If there is any accidental change occurred on the pointer, this technique helps you to get the actual address of allocating memory that is needed at the time of memory deallocation.

Avoid the orphaning memory location

At the time of memory deallocation, we need to free the memory from child to parent that means a child will be free first. If we free the parent first, it can be a cause of memory leak.

For example,

In below code, the pointer to context structure is freeing first. So the pointer that is pointing to space for the information data become orphan and it can be a cause of memory leak.

 

Write the proper comments

I think it is good habits to write the comment in every section of the code. It always reminds you that what you did. It helps you if you read your code after some months or years.


Leave a Reply