delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2000/02/19/13:09:28

From: "-hs-" <email DOT invalid AT server DOT invalid>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: new vs malloc
Date: Sat, 19 Feb 2000 15:32:11 +0100
Lines: 68
Message-ID: <88m9hb$7ar$1@news2.isdnet.net>
References: <38AD8622 DOT AE067F97 AT tiscalinet DOT it> <004101bf7a97$06ff2ca0$cff0fea9 AT stevenhe> <88lt6e$9pj$1 AT nets3 DOT rz DOT RWTH-Aachen DOT DE> <01bf7ba9$8fb5a980$c3247d81 AT default>
NNTP-Posting-Host: d164.paris-161.cybercable.fr
Mime-Version: 1.0
X-Trace: news2.isdnet.net 950970731 7515 212.198.161.164 (19 Feb 2000 14:32:11 GMT)
X-Complaints-To: abuse AT isdnet DOT net
NNTP-Posting-Date: 19 Feb 2000 14:32:11 GMT
X-Newsreader: Microsoft Outlook Express 4.72.3110.5
X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

doug a écrit dans le message <01bf7ba9$8fb5a980$c3247d81 AT default>...
>> In a nutshell: if you write C++, use new. If you write C, use
>> malloc(), and *don't* cast the return value, as it will actually hide
>> potential problems, instead of fixing any.
>
>Can you give me an example.   I like my C programs to compile
>with as few warnings as possible, even if they are compiled as C++
>and I cast the returned value from malloc to achieve this.  Can you
>give me an example of where this casting may cause problems in
>a C program?
>
>Thank you,
>
>Doug Eleveld

This is a Bad Code:

int main (void)
{
char *p=malloc(20);
   if (p)
   {
      free(p);
   }
   return 0;
}

Why ? Simply because <stdlib.h> is missing, that implies that the default
return type of malloc() is int (also the parameters).

But int can't be converted implicitally to char* by the compiler. So the Bad
Programmer will cast the returned value.
char *p=(char *)malloc(20);

That will tell the compiler, "Shut up ! I know what I am doing !" (Actually
a flaw)

The lack of prototype will alllow such a monster

char *p=(char *)malloc(-20,"big bug");

The Good Programmer (gently warned by the compiler) will simply add the
missing <stdlib.h> and all will come back to happyness and joyful. The bugs
will be smashed.

This is a Good Code:

#include <stdlib.h>

int main (void)
{
char *p=malloc(20);
   if (p)
   {
      /* do safely your duty here... */
      free(p);
   }
   return 0;
}

--
-hs-
CLC-FAQ: http://www.eskimo.com/~scs/C-faq/top.html
ISO-C Library: http://www.dinkum.com/htm_cl
"It's specified. But anyone who writes code like that should be
transmogrified into earthworms and fed to ducks." -- Chris Dollin CLC


- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019