The function free()
does not prevent access to any address. Any attempt to access an address will be successful (all right, it has a protection exceptions, but it does not come to the case for this example).
C is a language that does not prohibit you from accessing undesirable data. If you want to access an address it will be accessed, no matter if you have what you want or not, it is your responsibility to ensure that access is appropriate and produces the intended result.
free()
does not erase any data, it remains there until some operation writes over it. And the address will still be accessible even after that, only now it has a piece of data that’s not the same. Nothing informs you that you are wrong, if you are not careful you will cause problems, potentially serious. Not to mention the security failure.
The only thing the function does is indicate to the used memory manager that that address can be used for something else when you need it.
So, contrary to what you might be imagining, the function malloc()
does not create a pointer, just reserves a space in memory and returns a pointer to that address. This pointer is just an address, it has nothing special. It is like having 10 real in the wallet. There are only 10 real, there are 10 real that can only be used to pay for a sandwich in your Manuel’s bakery.
If you want guarantees look for a language with automatic memory management, or at least secure, it is not the case of C that is a powerful language, fast and flexible, not secure. Security is given by you.
I would just like to know why this is because I needed the released pointer to be equal to NULL (which I thought the function
free()
did), but even after releasing the memory, it means I can set the pointernew
to NULL that will work ?– Matheus
Yes, it will, and you can continue accessing the pointer, only you can no longer access the object, if you try it will give error.
– Maniero