Reputation: 45
It is said to be good practice to set a pointer to NULL after freeing the memory, from a security point of view. What happens if you set the pointer to NULL before freeing the memory? How would this cause a vulnerability?
Upvotes: 0
Views: 1487
Reputation: 1068
I think you misunderstood the reason it is set to NULL
after freeing the memory. You dont want to touch memory that is not yours.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a = malloc(sizeof(int));
free(a);
printf("%p", a);
*a = 1;
return 0;
}
We free the pointer, but it still points to the same address. And i can write to it "no problem". Actually in this case you get into undefined behavior.
So if you free the pointer, and use it later, you are setting up for disaster. But if you set it to NULL, then you will segfault. Like in this case.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *a = malloc(sizeof(int));
free(a);
printf("%p", a);
a = NULL;
*a = 1;
return 0;
}
So if you dereference a freed pointer, at least you will get to know it for sure while you test the app.
Now if you set it to NULL before freeing the memory, you will just leak memory. It is still bad.
Upvotes: 5
Reputation: 164689
What happens if you set the pointer to NULL before freeing the memory?
If you try to free a null pointer, nothing will happen.
If there are other pointers to the same memory, they can continue to be used to reference and eventually free the memory.
If that's the only pointer to that memory, the memory cannot be referenced again. The process will hold onto the memory until it exits. It is a "memory leak".
Processes with memory leaks will use more and more memory. Leaks are common enough that long running processes and even entire servers are habitually restarted daily.
Upvotes: 3