Casting malloc() in ANSI C?

Mark William Hopkins markh at csd4.csd.uwm.edu
Wed Dec 27 04:40:29 AEST 1989


In article <24969 at cup.portal.com> Kevin_P_McCarty at cup.portal.com writes:
>This is a question on recommended style.
>
>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?

One way around the issue is to define the macro:

#define make(Type) (Type *)malloc(sizeof(Type))

or, perhaps:

#define make(Type, N) (Type *)malloc((N)*sizeof(Type))

and use it to replace malloc as much as possible.

If you're going to use information about the Type anyway (in sizeof()), you
might as well cast malloc and then hide everything.

So you can have it both ways: extra (potentially useful) information,
without the clutter, and not only that, but with LESS clutter than if you
had just decided to eliminate the type casting out of a concern for making
the code less cluttered.

And if that isn't enough, you can modify it easily without ever even touching
on the issue of whether malloc should be casted or not:

#ifdef ANSI
#define make(Type) malloc(sizeof(Type))
#else
#define make(Type) (Type *)malloc(sizeof(Type))
#endif

... presumably this would be in a header file, all invisible to the normal
programmer.



More information about the Comp.lang.c mailing list