Casting malloc() in ANSI C?

Walter Bright bright at Data-IO.COM
Thu Dec 14 08:41:20 AEST 1989


In article <24969 at cup.portal.com> Kevin_P_McCarty at cup.portal.com writes:
<In ANSI C, assigning a void pointer to any pointer variable is
<legal, so casting the value returned by malloc() to the
<appropriate pointer type is no longer necessary.  As a matter of
<recommended style, should the redundant cast be retained?

Yes. In C++, implicit casts of (void *) to (any *) is not allowed.
The 'redundant' cast is required in C++ code. Since C++ is the way
C is moving, leave the cast in.

<- When the appropriate header is ommitted, a cast will suppress a
<helpful diagnostic, and at worst can result in the return value
<from malloc() being silently munged beyond use.

C++ solves this problem by *requiring* functions to be prototyped before
use. This eliminates the nasty problems caused by forgetting to declare
malloc.

<- Some ANSI-aware compilers will complain upon encountering a
<function call for which no prototype has been seen.  This is a
<Good Thing, to be encouraged, but is a quality of implementation
<issue and can't be relied on.

It's required in C++, and can be relied on.



More information about the Comp.lang.c mailing list