Malloc in Turbo C

Lawrence H. Miller lmiller at aerospace.aero.org
Wed Feb 28 08:20:27 AEST 1990


In article <26316 at qfagus.OZ> gordon at qfagus.OZ (Peter Gordon) writes:
>
>Asks why the following code produces anomalous results with Turb C.

(various header files removed for clarity)

main()
{
	char **head, **cp;
	int	i;
	head = (char **)malloc(200 * sizeof(char **));
	for(cp = head, i = 0; i < 200; ++i, ++cp)
	{
		fprintf(stdout,"Freeing %d\n", i);
		fflush(stdout);
		free(cp);
	}
}

>From a VERY early draft of the ANSI C standard:

	void free(void *ptr)

	...if the argument does not match a pointer earlier returned by
	the calloc, malloc, or realloc function, or if the space has been
	deallocated by a call to free or realloc, the behavior is
	undefined.

Your first call to free frees all the allocated space.  Subsequent calls
to free using a pointer into freed space, produces undefined behavior.

Here is the definition of "Undefined behavior":

	Behavior for an erroneous program construct, for which the standard
	imposes no requirements.  Permissible undefined behaavior ranges
	from ignoring the situation completely with unpredictable
	results...to terminating a[n]...execution with a diagnostic
	message.
Larry Miller
Aerospace Corporation
lmiller at aerospace.aero.org
213-336-5597



More information about the Comp.lang.c mailing list