Casting malloc() in ANSI C?
Mark Brader
msb at sq.sq.com
Tue Dec 19 19:10:11 AEST 1989
An article which, curiously, was posted to the USA only, asks:
> 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?
I would advise retaining the cast for a few years until (a) there *is*
such a thing as ANSI C, and (b) its use is widespread. Before that time
there is too much probability of wanting to port back to older compilers.
Once such porting really is not a problem, then I would strongly recommend
removal of the cast. The statements
foop = malloc (sizeof *foop);
foolistp = malloc (n * sizeof *foolistp);
contain NO MENTION of the type of *foop or *foolistp, which makes it
impossible to get it wrong.
Those who say "implicit type conversion is a bug, not a feature" will
disagree. My opinion is that it is a feature.
A followup suggested that the cast is required in C++ and should there-
fore be used in C. My opinion is that C++ should "therefore" be fixed.
--
Mark Brader "'A matter of opinion'[?] I have to say you are
SoftQuad Inc., Toronto right. There['s] your opinion, which is wrong,
utzoo!sq!msb, msb at sq.com and mine, which is right." -- Gene Ward Smith
This article is in the public domain.
More information about the Comp.lang.c
mailing list