Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out whether the address supplied to free() is an invalid address?

Tags:

c

linux

free

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.

like image 294
RajSanpui Avatar asked Dec 28 '22 18:12

RajSanpui


2 Answers

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.

like image 60
Andrew Aylett Avatar answered Jan 19 '23 00:01

Andrew Aylett


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.

like image 33
Jacek Konieczny Avatar answered Jan 18 '23 22:01

Jacek Konieczny