Is there any way to find out whether an address supplied to free( )
is an invalid address, before calling the free( )
?
We know free( )
creates an undefined behaviour if the address is an invalid address (already freed address). So how to make sure that address is a valid one?
Thanks in advance.
If you need to do this, you have a bigger problem -- you have free'd your memory before you've finished with it, or you've not invalidated references to memory when you've finished with it. Rather than trying to stop your program double-freeing by changing free()
, you should be trying to fix your pointer lifetime issues.
You may find that Valgrind can help you to work out where things are going wrong.
The behaviour on free()
for invalid address is undefined, because it is unpredictable. In a low-level language like C you cannot say if address is 'valid' or 'invalid'. And there are many ways a address may be invalid. 'Already freed' is only one of the cases other include: address not allocated by malloc, the data is not actually an address (e.g. some integer or character string casted to pointer), data corruption, etc.
If you are interested in the 'already freed' case only you could try to track every memory allocation and deallocation (e.g. by using a custom malloc()
and free()
wrapper) but this would probably only make your code more complicated and even more error-prone.
Simple answer: no, there is no way to check if the address is invalid. Live with it or switch to a higher level language (like e.g. Python), when you don't care about memory addresses at all.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With