Barry said:
An example please for those of us with limited imaginations.
For the side against casting malloc:
[markg@cpa-re-test ~]1002$ cat t.c
int main(void)
{
return malloc(9);
}
So is it to be understood that are offering a program which contains no casts
whatsover as a counterexample against casting?
If we add the cast, then we catch an error:
int main(void)
{
return (void *) malloc(9);
}
gcc will now diagnose this even if given no warning options:
test.c: In function `main':
test.c:3: warning: return makes integer from pointer without a cast
So, in summary:
- no cast: the broken program compiles without a hitch.
- cast added: a diagnostic is produced.
Looks like you lose.
It so happens that an installation of gcc I have here also silently accepts
this program, in which there is no cast:
int main(void)
{
char *str = malloc(9);
return 0;
}
If I add the cast, it also silently accepts the program. Oops!
Maybe using gcc installations to prove your case is not such a hot idea.
It depends on what version of gcc you are using. The one which accepts the
program with or without a cast is 3.4.3.
Version 4.3.2 prints this:
test.c: In function main:
test.c:4: warning: incompatible implicit declaration of built-in function malloc
That's with, or without the cast, doesn't matter.
Two wrongs don't make a right. The ability to call functions without declaring
them is an unfortunate hole in the C type system. The ability to convert from
void * without a cast is also an unfortunate hole in the type system.
Yes, so there are situations in which there is a tradeoff between risk between
two holes: cast the return of a function and you cover up the bad function
call. Don't cast the return value, and you subvert the type system via void *,
without a cast. Which poison to choose?
Let's see, I can deal with the first hole by using a decent compiler with good
diagnostics, so that I never call an undeclared function. So I don't have to
worry about the cast covering up a bad function call.
Few C compilers provide a diagnostic against the second hole (warning for
a void * being converted to a pointer to object type).
So it's illogical to assert that when there is an unfortunate conflict between
two type system holes, the programmer should cater to the hole which is easily
fixable with widely available technology, and ignore the one which isn't.
[markg@cpa-re-test ~]1003$ gcc t.c
This is on a server running a still commercially supported version of
Linux. The server in question is the one we use to do our official
software builds.
And these offical builds of yours take the form of ``gcc file.c -c'' with no
arguments to the compiler? And do do you use a half-decade old gcc that
came with your Linux server, for your official builds? Then you deserve
whatever you get.