-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Rob wrote:
int *p;
p = malloc(1);
free(p);
/* */
In the above code, how do I detect that variable p points to nothing?
In the above code, you don't (and can't) "detect that variable p points to nothing".
In other words, how do I detect a freed memory pointer, as opposed to a
pointer that points to allocated memory?
You detect it by not using it. It's your code, and you are assumed to know what
you are doing. You are in control; you allocate the pointer variable, fill it
with a pointer to storage, and then subsequently dispose of the storage. You do
this explicitly. It behoves you, as a competent programmer to then /not/
dereference the pointer variable that you /know/ no longer points to storage.
Having said that, there are techniques that /you/ can employ that will permit
you to be lax in tracking whether or not pointer variables point at storage. One
such technique is to assign the pointer variable a NULL value whenever the
pointer no longer points to allocated storage. Something like
{
char *p = NULL;
p = malloc(1);
free(p); p = NULL;
}
With this, a simple test before dereferencing will suffice...
if (p) *p = 100;
I'm sure you can come up with other methods of protecting yourself when you are
less than thorough in your handling of pointer variables.
- --
Lew Pitcher
IT Specialist, Enterprise Data Systems,
Enterprise Technology Solutions, TD Bank Financial Group
(Opinions expressed are my own, not my employers')
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (MingW32)
iD8DBQFDFvBFagVFX4UWr64RArtmAJ9qCfsS65UXU74Pr+c7g7 V41Xe5gQCeONVE
j+dalVn2+yk0wJzmNDLnSuA=
=KwfF
-----END PGP SIGNATURE-----