(e-mail address removed) wrote
(in article
Dear All,
Is it true that we can use dynamically-allocated memory after we free
it. ?
Not at all. It is true that a lot of people /try/ to do this,
and generally suffer the consequences. One very unfortunate
aspect of undefined behavior in C programs is that sometimes
code that is demonstrably broken will accidentally work anyway,
and the result of this seemingly unlikely result is to convince
programmers that they can get away with it. The truth is that
they just got very UNlucky and may not realize it until much
later.
And if it is possible then how to make it sure that it can not be
used once we have freed
the dynamically allocated memory in our program.
It's all but impossible to guarantee it won't happen through
some crutch method or language feature. however, you can code
to avoid it or perhaps eliminate it, if you are careful. There
is no foolproof method that I am aware of other than programmer
skill. Some folks always check for NULL before dereferencing a
pointer, and nevermind the performance consequences (I am one of
those). Some folks replace free() with a version to sets the
pointer to NULL afterward. That works in some, but not all
cases.
In any event, if someone told you it was okay to use it after
the fact, you owe it to the universe to convince them otherwise
before they spread such code around further. If you read it in
a book, please let us know the source.