Turboc Malloc

D'Arcy J.M. Cain darcy at druid.uucp
Fri Mar 2 00:57:45 AEST 1990


In article <26317 at qfagus.OZ> gordon at qfagus.OZ (Peter Gordon) writes:
>
>>	Please tell me I'm doing something stupid.
>>		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);
>>		}
>>	}
>My face is red, as suspected the fault is mine and is stupid.  I'm
>freeing a pointer and THEN trying to increment it.
>Code something like:
>X	for(cp = &head[198]; cp >= head; --cp)
>X		free(cp + 1);
>X	free(head);
>works as expected.  People abuse the bugs in compilers, but in many
>instances, they are very forgiving of fools such as I.
>
>Peter Gordon

Sorry.  It's getting redder.  To free the memory allocated by the malloc
you simply do:
    free(head);
once.  No loop required, one free frees the entire block allocated.  What
you are doing may even work on most compilers and OS's simply because most of
the calls to free are ignored.  (They ae undefined in fact.)  This may lead
you to believe that you can free head[0] and then access head[27].  Expect
to dump core on a standard UNIX box or anything with good memory protection
if you do this.

BTW: Perhaps you should explain *exactly* what it is this code is trying
to accomplish.  With that knowledge I am sure someone can suggest the
best way of doing what you want to do.

-- 
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