Path: utzoo!attcan!telly!druid!darcy From: darcy@druid.uucp (D'Arcy J.M. Cain) Newsgroups: comp.lang.c Subject: Re: Turboc Malloc Keywords: Turboc Malloc Message-ID: <1990Mar1.135745.17086@druid.uucp> Date: 1 Mar 90 13:57:45 GMT References: <26317@qfagus.OZ> Reply-To: darcy@druid.UUCP (D'Arcy J.M. Cain) Organization: D'Arcy Cain Consulting, West Hill, Ontario Lines: 41 In article <26317@qfagus.OZ> gordon@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@druid) | Thank goodness we don't get all D'Arcy Cain Consulting | the government we pay for. West Hill, Ontario, Canada | (416) 281-6094 |