Mail Archives: djgpp/2000/02/19/13:09:28
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 -