Path: utzoo!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!samsung!brutus.cs.uiuc.edu!psuvax1!psuvm!cmh117 From: CMH117@psuvm.psu.edu (Charles Hannum) Newsgroups: comp.lang.c Subject: Re: Malloc in Turbo C Message-ID: <90058.153755CMH117@psuvm.psu.edu> Date: 27 Feb 90 20:37:55 GMT References: <26316@qfagus.OZ> Organization: Penn State University Lines: 67 In article <26316@qfagus.OZ>, gordon@qfagus.OZ (Peter Gordon) says: > >Please tell me I'm doing something stupid. The following code works on Okay. You're doing something really stupid. {B-) JOKE B-) JOKE B-) JOKE} >Microsoft C and a MIPS/1000 runnung UNIX Sys V Release 4_0. It shouldn't. You were lucky. >On Turbo C (ver 2) it crashes after a variable number of frees. I've tried >all memory models and far pointers and can't think of much else to >try. Commonsense tells me that such a basic bug would not be >in Version 2, would some kind person point me in the right direction. Okay, I'll give you a few pointers. ;-) >#include >#ifdef __TURBOC__ >#include >#else >#include >#endif >#include >main() >{ > char **head, **cp; ~~~~~~~ A "char **" is a "pointer to a char *" (or, to make Chris Torek cringe, a "pointer to an array??(SIZE_UNKNOWN??) of char *'s) (Note: Excuse the ASCII tryglyphs; I'm using an IBM 3179G terminal right now.) > int i; > head = (char **)malloc(200 * sizeof(char **)); ~~~~~~~ Thus, you really want to allocate space for 200 "char *"s; but this is not why it crashes. (The pointers are the same size, anyway.) > for(cp = head, i = 0; i < 200; ++i, ++cp) > { > fprintf(stdout,"Freeing %d\n", i); > fflush(stdout); > free(cp); I almost cried when I saw this. You are trying to free the space for the 200 "char *"s independently. You can't do that; you allocated them as one block, and you must free them as one block. Please, PLEASE, read K&R2, or the Turbo C user's guide!! > } >} As a side note: No insult intended against you, but this is a prime example of why we need to teach people a programming language before we expect them to use it. The concept of pointers is so basic to the C language that it seems impossible that you've had any formal education in the language. Is it that you've never had the opportunity, never had the time, or never had the need before? And have you considered taking a class (assuming one is available)? Virtually, - Charles Martin Hannum II "Klein bottle for sale ... inquire within." (That's Charles to you!) "To life immortal!" cmh117@psuvm.{bitnet,psu.edu} "No noozzzz izzz netzzzsnoozzzzz..." c9h@psuecl.{bitnet,psu.edu} "Mem'ry, all alone in the moonlight ..."