Path: utzoo!utgpu!jarvis.csri.toronto.edu!torsqnt!hybrid!robohack!druid!darcy From: darcy@druid.uucp (D'Arcy J.M. Cain) Newsgroups: comp.lang.c Subject: Re: Malloc in Turbo C Keywords: Turbo C Malloc Message-ID: <1990Feb28.155343.3670@druid.uucp> Date: 28 Feb 90 15:53:43 GMT References: <26316@qfagus.OZ> Reply-To: darcy@druid.UUCP (D'Arcy J.M. Cain) Organization: D'Arcy Cain Consulting, West Hill, Ontario Lines: 40 In article <26316@qfagus.OZ> gordon@qfagus.OZ (Peter Gordon) writes: > >Please tell me I'm doing something stupid. OK. You're doing something stupid. :-) >#include >#ifdef __TURBOC__ >#include >#else >#include >#endif >#include >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@druid) | Thank goodness we don't get all D'Arcy Cain Consulting | the government we pay for. West Hill, Ontario, Canada | (416) 281-6094 |