effect of free()

Doug Gwyn gwyn at smoke.BRL.MIL
Sat Sep 9 10:34:02 AEST 1989


In article <247 at ssp1.idca.tds.philips.nl> dolf at idca.tds.PHILIPS.nl (Dolf Grunbauer) writes:
>What about the case when ptr is already in a register
>(i.e. definition of ptr: register char *ptr) ? Will there be an address trap
>right after the free as some address register now holds an invalid address ?

No, provided that you don't try to copy the now-defunct address into some
other variable or to use it in any other way.  Storing a valid address in
place of the defunct one would of course be okay.

>By the way: what is the effect of the address trap: does the "if (ptr == 0)"
>always evaluate to FALSE or is there a signal (SIGSEGV) ?

If there is a trap, in a UNIX environment a signal would be synchronously
posted for the process.  Which signal number is used is left up to the OS
implementor.  In other environments, other things might happen.
Undoubtedly it would not be something the programmer would WANT to happen.

>If so: how can I check in my program whether ptr is still valid (after all
>that's why we had the "if (ptr == 0)" in the first place :-) ?

You don't have to check.  You know that it will be invalid after free(ptr).

For other uses, you can set a boolean flag before the free(ptr) then rely
on the flag later to control further flow of execution.

>If "if (ptr == 0)" cases some sort of a trap or is illegal, is the expression
>"if ((long)ptr == 0)" legal, as ptr will now be loaded in a data register
>instead of an address register (assuming: sizeof(cahr *) == sizeof(long)) ?

No, reading the contents of ptr at all after free(ptr) is a non-portable
operation.  "Data" and "address" registers are mentioned merely in this
discussion of possible ways the operations might be implemented.  They
are not required to be implemented like this.

>A final question: how valid is this discussion ? Is there any CPU (commercial
>available) which has this sort of address checking ?

One of the Multics programmers mentioned a Honeywell machine like that.
I believe Intel's iAPX432 and IBM's System/38 architectures may support
implementations such as we've mentioned.



More information about the Comp.lang.c mailing list