Reputation: 1215
As you know, after we finish using dynamic variables we free()
them.
However, sometimes those variables are already free()
d.
I need to check if it is free to avoid double free. Would anyone give me a clue?
Upvotes: 1
Views: 2458
Reputation: 124692
You can't check if it's already been free
'd (the signature of free
should tell you that much; it can't modify the pointer from the caller's perspective). However, you can do one of two things.
Change your design. Who is responsible for this memory? It seems as though your design does not make that clear, which is the most common reason for memory leaks. Place ownership on one part of your code and be done with it. Why would the interrupt function conditionally deallocate the memory? Why does that seem like the most logical solution?
Set the pointer to null
and double free all you like. free(NULL)
is perfectly valid.
I prefer option 1 and learning this lesson now will help you write better code down the road.
Upvotes: 13
Reputation: 25129
+1 to Ed S.'s answer.
But also, run valgrind
- it will pick up many dynamic memory allocation errors quickly, and may be better at reading your code than you are.
Upvotes: 4