Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!samsung!zaphod.mps.ohio-state.edu!usc!elroy.jpl.nasa.gov!aero!aerospace.aero.org!lmiller From: lmiller@aerospace.aero.org (Lawrence H. Miller) Newsgroups: comp.lang.c Subject: Re: Malloc in Turbo C Keywords: Turbo C Malloc Message-ID: <67582@aerospace.AERO.ORG> Date: 27 Feb 90 21:20:27 GMT References: <26316@qfagus.OZ> Sender: news@aerospace.aero.org Reply-To: lmiller@batcomputer.UUCP (Lawrence H. Miller) Organization: The Aerospace Corporation, El Segundo, CA Lines: 42 In article <26316@qfagus.OZ> gordon@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@aerospace.aero.org 213-336-5597