Malloc in Turbo C

Charles Hannum CMH117 at psuvm.psu.edu
Wed Feb 28 07:37:55 AEST 1990


In article <26316 at qfagus.OZ>, gordon at 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       <stdio.h>
>#ifdef __TURBOC__
>#include       <alloc.h>
>#else
>#include       <malloc.h>
>#endif
>#include       <stdlib.h>
>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 at psuvm.{bitnet,psu.edu}  "No noozzzz izzz netzzzsnoozzzzz..."
  c9h at psuecl.{bitnet,psu.edu}    "Mem'ry, all alone in the moonlight ..."



More information about the Comp.lang.c mailing list