L
Leor Zolman
pete said:Leor said:David Scarlett wrote:
Is the following code safe?
No.
Hmmm. Assuming a was valid before the free() and b still is at the
point of the comparison, I don't get why you think this is unsafe.
Personally, it seems strange to test the value of a pointer after it
has been freed (and your version is more conventional in that sense),
but since we're only testing the /pointer/ and not trying to access
the memory it is pointing to, why wouldn't the OP's code be "safe"?
-leor
N869
7.20.3 Memory management functions
[#1]
The value of a pointer
that refers to freed space is indeterminate.
So the correct thing for a compiler to do after call "free (a)" would be
to treat a the same as an uninitialised variable (uninitialised
variables have indeterminate values as well), giving a warning when you
try to use it and so on.
As I understand it, violations of things not in a "Constraints" section of
the Standard are not required to draw a diagnostic; compilers are free to
emit or not emit diagnostics as they please (IOW, it is a compiler QOI
issue).
In any case, this sounds more like something that might fall into the
domain of a lint-like program, if anywhere, rather than the compiler.
Consider code such as the following:
char *p, *q, *r;
p = malloc(...);
q = malloc(...);
r = q;
...
free(q);
...
if (p == r ) /* oops, can't test q...er, r! */
...
Would you expect a compiler to be "smart enough" to know that testing r is
actually testing the freed value of q, and warn about it?
-leor