Malloc in Turbo C

D'Arcy J.M. Cain darcy at druid.uucp
Thu Mar 1 02:53:43 AEST 1990


In article <26316 at qfagus.OZ> gordon at qfagus.OZ (Peter Gordon) writes:
>
>Please tell me I'm doing something stupid.
OK.  You're doing something stupid.  :-)

>#include	<stdio.h>
>#ifdef __TURBOC__
>#include	<alloc.h>
>#else
>#include	<malloc.h>
>#endif
>#include	<stdlib.h>
>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);
>	}
>}
The first call to free(cp) frees up the entire memory allocated by malloc.
The functions malloc and free don't have any idea what the allocated space
is used for and don't know what size the items are.  The value returned by
malloc is a pointer and the argument to free is a previously returned
pointer.  For 199 times in the above code you are freeing pointers that
haven't been allocated.  in malloc(3C) this is stated to produce undefined
results so you got what was promised.

Also, even given what you were trying to do, didn't you mean 'cp++' in
the for loop statement, not '++cp'?

-- 
D'Arcy J.M. Cain (darcy at druid)     |   Thank goodness we don't get all 
D'Arcy Cain Consulting             |   the government we pay for.
West Hill, Ontario, Canada         |
(416) 281-6094                     |



More information about the Comp.lang.c mailing list