effect of free()

david.f.prosser dfp at cbnewsl.ATT.COM
Sat Aug 19 00:17:23 AEST 1989


In article <16022 at vail.ICO.ISC.COM> rcd at ico.ISC.COM (Dick Dunn) writes:
>bill at twwells.com (T. William Wells) writes:
>> ...For example, the following code fragment is nonportable:
>> 
>> 	ptr = malloc(1);
>> 	free(ptr);
>> 	if (ptr == 0) ...
>> 
>> The if might cause a trap when the value of ptr is accessed.
>
>Not true.  The "if" only examines the value of the pointer, not what it
>points to.  free(ptr) does not modify ptr; it can't.  Assuming the malloc
>succeeded (and assuming an appropriate in-scope declaration of malloc, if
>you want to be fussy), the code as written will work, and the body of the
>"if" will not be executed, since ptr will be non-null from the malloc.
>
>The trouble will only begin when you try to look at *ptr.

Not according to the pANS.

Section 4.10.3, page 155, line 20:

	The value of a pointer that refers to freed space is indeterminate.

>From the definition of undefined behavior, section 1.6, page 3, lines 23-25:

	Undefined behavior -- behavior, upon use of a nonportable or erroneous
	program construct, of erroneous data, or of indeterminately-valued
	objects, for which the Standard imposes no requirements.

Thus, an architecture is free to trap on the above code.  This was a
deliberate choice of the Committee.

Dave Prosser	...not an official X3J11 answer...



More information about the Comp.lang.c mailing list