What is double free in C programming
Introduction
In C there are two different ways to allocate memory, one way is static memory allocation and another one is dynamic memory allocation. Static memory is handled by OS and based on scope of memory literal it will be freed. While dynamic memory allocation has to handled by programmer which way it gives more control to deal with memory. But giving more access to memory might cause some issues like memory leak, memory corruption etc. One of the issue might occur is Double Free issue.
As name suggest freeing memory more than once can cause the double free issue.
How it happens ?
When calling free() more than once for the same variable can lead various issues like memory leak, corruption etc. This can lead to allow malicious user to write values in the arbitory memory spaces. This type of corruption can cause the program crash or some undefined behaviour. By overwritting a particular registers or memory space, attackers might trick the program and can lead to disruption of the original execution flow.
Visible Issues
- Program might crash which means execution of program is abruptly terminated.
- Program might lead to generating the core dump.
- If program doesn’t have exit criteria defined then crashing might lead to restarting and crashing again. This eventually increase the CPU utilization and will create undefined behaviour.
Program sample which leads to double free
Execute the above code and program gets terminated
If you observe the code execution of the above program, it shows “free() double free detected“.
And program execution gets aborted which leads to core dump.
This way if free() is called more than once then your program is having high vulnerability. It is never safe.
How to avoid double free issue.
- Once the free() is called then assign that variable to NULL.
- Before free() check if that variable is not NULL then only free().
- Write your own safe free function to handle free and make it standard way to follow.
Programming Advice
Whenever you allocate memory via dynamic memory allocation method then it is advisable to free() that memory. Make sure there is no double free() issue introduce by your code. Always force to use safe_free() function as standard practice.
If you feel you have learn something new, or in any way this articled helped you then please share this article with your techie friends and save your code from crashing.
Also if you feel what we are doing is right way then please donate us to help you in better way.