How do I know if the address specified in free () is an invalid address?

Is there a way to find out if the address specified in free( ) invalid address before calling free( ) ?

We know that free( ) creates undefined behavior if the address is an invalid address (an already freed address). So how do you make sure the address is valid?

Thanks in advance.

+4
source share
4 answers

If you need to do this, you have a big problem - you freed up your memory before you finished with it, or you didn’t invalidate the memory references when you finished with it. Instead of trying to stop the program from double-freeing by changing free() , you should try to fix your problems with the pointer life cycle.

You may find that Valgrind can help you figure out where everything goes wrong.

+6
source

The behavior on free() for an invalid address is undefined because it is unpredictable. In a low-level language like C, you cannot tell if the address is "valid" or "invalid". And there are many ways in which an address can be invalid. Already freed is only one of the following cases: an address not assigned by malloc, data is not really an address (for example, some integer or character string passed to a pointer), data corruption, etc.

If you are only interested in the “freed” case, you can try to track the allocation and freeing of memory (for example, using the malloc() and free() user shell), but this will probably only make your code more complex and even more error prone.

The simple answer is no, there is no way to check if the address is invalid. Live with it or switch to a higher level language (like Python) when you don't care about memory addresses at all.

+2
source

No.

To be more useful, we really need to know your intended use case.

If you use the same pointers that sometimes refer to memory obtained using malloc , and in other cases refer to string literals or automatic variables, then you should just store a flag next to a pointer that indicates whether it points to something received by malloc . Or you can just save a second copy of the pointer called ptr_to_free , which is NULL when the data does not need to be freed. This also has the advantage that your “main pointer” can “move” and point to different parts of the object, since you will keep the original / base pointer free separately.

If you just need to avoid double-release issues, you just need to fix your code so that they don't exist. Setting the pointer to NULL immediately after you release what it points to is a careless trick that will usually get you most of the way, but you probably have more design problems to rethink ...

+2
source

As others have shown, pointer tracking is a good way to find out if memory is freed or not.

I also suggest the following pointers.

  • Initialiase pointer to NULL when you declare it
  • Once released, you initialize it to NULL again.
  • Check to see if the pointer is non-NULL before trying to free.
0
source

All Articles