That was the example I had in mind.
Code: Select all
#include <stdlib.h>
int main(void)
{
struct mystrct *pstrct = malloc( sizeof *pstrct );
return 0;
}
will compile without problems on a C compiler. C++ does not allow implicit
conversion from void* to any other type. So if you wanted this to get compiled
on a C++ compiler as well you'd have to write something like:
Code: Select all
#include <stdlib.h> // yes, I know about <cstdlib> :)
int main(void)
{
struct mystrct *pstrct = (struct mystrct *)malloc( sizeof *pstrct );
return 0;
}
The C committee is to be blamed for this subtle difference in dialect
of the two languages which otherwise has a broad common ground
(this particular usage of void * was borrowed from C++.)
However, have no prejudice and keep in mind it is not required in C but it
is allowed

As for C++, the need goes away when you use new
instead. Here's a bit more story:
All examples in K&R2 are valid C++, with the same semantics as in C.
The authors have publicly admitted that this was a mistake on their
part

This is from the K&R2 errata:
142: The remark about casting the return value of malloc ("the proper
method is to declare ... then explicitly coerce") needs to be
rewritten. The example is correct and works, but the advice is
debatable in the context of the 1988-1989 ANSI/ISO standards. It's not
necessary (given that coercion of void * to ALMOSTANYTYPE * is
automatic), and possibly harmful if malloc, or a proxy for it, fails
to be declared as returning void *. The explicit cast can cover up an
unintended error. On the other hand, pre-ANSI, the cast was necessary,
and it is in C++ also.