473,889 Members | 1,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why is casting malloc a bad thing?

Hello,

I saw on a couple of recent posts people saying that casting the return
value of malloc is bad, like:

d=(double *) malloc(50*sizeo f(double));

why is this bad? I had always thought (perhaps mistakenly) that the
purpose of a void pointer was to cast into a legitimate date type. Is
this wrong? Why, and what is considered to be correct form?

thanks,

Brian Blais

Nov 14 '05
231 23347
On Tue, 27 Jan 2004 00:55:08 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:dl******* *************** **********@4ax. com...
Anyway to respond to you now, sorry, but I won't retract. I've read
through his reasoning several times, and its IMHO wrong. Since he
persists in holding a wrong position, I consider him idiotic on this
point.
Note that this isn't a general position, merely on the malloc point.


I've now accumulated enough evidence that you're incapable of
reading accurately what others write, particularly when you don't
agree with them.


The only way you can have achieved that accumulation is by failing to
read properly what I've written myself. So I propose to stop being
interested in your postings, to avoid further unpleasantness.
We've been over it many many times, and while I appreciate his work
circumstances make it much more convenient for him to cast malloc,
thats not a valid reason for advocating it to C programmers.


And you haven't even noticed that I'm *not* advocating this
position to C programmers in general.


Then your powers of explaination are much less good than you think.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #161
On Tue, 27 Jan 2004 00:48:38 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:qs******* *************** **********@4ax. com...
I recognised it very well indeed, and I elected to post anyway,
because I believe that when it comes to malloc casts, PJ has the
programming equivalent of a crush on a beautiful but unsuitable woman,
and is unable to see that she's stealing his money, sleeping with his
friends and using his house to sell dope from.... :-)
Now you're simply being a jerk.


And you, sir, have absolutely no sense of humour whatsoever. Come on,
you dolt, I'm not being nasty to you, you have one blind spot, I
forgive you, now grow up.
From your earlier posting:


(snip completely irrelevant requote)

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #162
Allin Cottrell wrote:
Sidney Cadot wrote:
With Mr. Plauger, I am amazed by the complete inability demonstrated
by many of the 'anti-cast' crowd to admit even a hint of nuance in
their thought process on this issue. Being 'pro-cast' myself...
As I see it, as a member of the 'anti-cast' crowd, the problem is
with the very notion of a 'pro-cast' position (a la Tisdale). We
see no possible rationale for this in terms of the C programming
language.
And that's ok for me. Limiting oneself to the context of the C
programming language (thus waiving the C++ compatibility argument for a
moment), I can see only one defense for malloc casting, which I
personally think is an important one: rigorous type discipline. if I
look at the free-standing expression "malloc(50*size of(double))" it is
clear that this should by intent be of type double*, but it is in fact
of type void*. I correct the compilers' misconception about this type by
a cast.

I know that in most contexts this isn't necessary because it will be
assigned to a typed pointer immediately after, but still it brings the
expression under the compiler's type checking regime a little bit
earlier, preventing such silliness as:

int *x = malloc(50*sizeo f(double));

since

int *x = (double *)malloc(50*siz eof(double));

is an error.

Now I've seen all the counter-arguments to this by now, but in the end I
simply feel that malloc(50*sizeo f(double)) is incorrectly typed as
void*, and that's all there is to it as far as I am concerned. Most here
disagree, their argumentation is clear and not without merit. I do feel
however that my stand on this is quite defensible, and will keep saying
so until either I or the whole lot of you changes sides ;-)
On the other hand, P.J. Plauger's basic position seems perfectly
reasonable, namely that there are some special contexts where a
body of code has to be compiled indifferently as C or as C++, and
in those special contexts casting the return from malloc is
required (and does no harm if we can assume that the coder is
astute enough to ensure that <stdlib.h> is always #included).

This, it seems to me, is not a 'pro-cast' position: it's just
saying that real-world considerations other than "good C
programming" sometimes dictate a cast. Fair enough.


Yes. Above, I try to put up a defense for the more extreme 'pro-cast'
position that doesn't invoke the C++ scenario. Feel free to dismiss it.

Best regards,

Sidney

Nov 14 '05 #163
Sidney Cadot wrote:
Limiting oneself to the context of the C
programming language (thus waiving the C++ compatibility argument for a
moment), I can see only one defense for malloc casting, which I
personally think is an important one: rigorous type discipline. if I
look at the free-standing expression "malloc(50*size of(double))" it is
clear that this should by intent be of type double*, but it is in fact
of type void*. I correct the compilers' misconception about this type by
a cast.

I know that in most contexts this isn't necessary because it will be
assigned to a typed pointer immediately after, but still it brings the
expression under the compiler's type checking regime a little bit
earlier, preventing such silliness as:

int *x = malloc(50*sizeo f(double));


Of course, that sort of silliness is taken care of (even if many lines
separate the

int *x;

from the malloc() call), by the clc recommended practice of

int *x = malloc(50 * sizeof *x);

--
Allin Cottrell
Department of Economics
Wake Forest University, NC
Nov 14 '05 #164
In <bv**********@n ews.tudelft.nl> Sidney Cadot <si****@jigsaw. nl> writes:
I know that in most contexts this isn't necessary because it will be
assigned to a typed pointer immediately after, but still it brings the
expression under the compiler's type checking regime a little bit
earlier, preventing such silliness as:

int *x = malloc(50*sizeo f(double));

since

int *x = (double *)malloc(50*siz eof(double));

is an error.

Now I've seen all the counter-arguments to this by now, but in the end I
simply feel that malloc(50*sizeo f(double)) is incorrectly typed as
void*, and that's all there is to it as far as I am concerned.


In most cases, malloc(50*sizeo f(double)) is considered bad style.
Consider the alternative:

double *x = malloc(50 * sizeof *x);

Casting to double * not only doesn't add anything, because there is no
place left for the error you're talking about, but it is a maintenance
headache if the type of x ever needs to be changed, say to pointer
to long double: instead of making one change, you have to make two,
for no redeeming advantage.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #165
Da*****@cern.ch (Dan Pop) wrote in message news:<bv******* ****@sunnews.ce rn.ch>...
In <XT************ *****@nwrddc01. gnilink.net> "P.J. Plauger" <pj*@dinkumware .com> writes:
Sorry, that's not quite right. The cast wasn't required in many/most
early C compilers. Some compilers experimented with stronger type
checking for pointers (a bit of the prior art we drew on when we
decided it was safe and advisable to add stronger type checking
in Standard C). Some of us felt that better documentation of
intended type conversions was advisable. But for whatever reason,
Kernighan at least went through a period when he saw fit to write
the casts.


IIRC, the pre-ANSI C mallloc returned char *. That required an
explicit cast any time its return value was not assigned to a char *.
So, it is very likely that Kernighan was doing it out of habit.

But there is another reason, mentioned in the preface:

We used Bjarne Stroustrup's C++ translator extensively for local
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^
testing of our programs, and Dave Kristol provided us with an ANSI
^^^^^^^^^^^^^^^ ^^^^^^^^
C compiler for final testing.

Since C++ requires the cast, the authors had no chance but to use it.


Dennis Ritchie and Brian Kernighan are among the most thoughtful of
people. They did have a choice at the time. If they had thought it
important/best to leave malloc calls uncast they could have (1) used
the ANSI C compiler or (2) edited the casts out in the final draft
(after the final check with the ANSI C compiler) or (3) politely asked
me for a compatibility feature in Cfront (we talked almost every day).

I think it is safest to assume that when Dennis Ritchie and Brian
Kernighan did something, it was because they wanted to do that and not
the opposite.

-- Bjarne Stroustrup; http://www.research.att.com/~bs
Nov 14 '05 #166
In <18************ **************@ posting.google. com> bs@research.att .com (Bjarne Stroustrup) writes:
Da*****@cern.c h (Dan Pop) wrote in message news:<bv******* ****@sunnews.ce rn.ch>...
In <XT************ *****@nwrddc01. gnilink.net> "P.J. Plauger" <pj*@dinkumware .com> writes:
>Sorry, that's not quite right. The cast wasn't required in many/most
>early C compilers. Some compilers experimented with stronger type
>checking for pointers (a bit of the prior art we drew on when we
>decided it was safe and advisable to add stronger type checking
>in Standard C). Some of us felt that better documentation of
>intended type conversions was advisable. But for whatever reason,
>Kernighan at least went through a period when he saw fit to write
>the casts.


IIRC, the pre-ANSI C mallloc returned char *. That required an
explicit cast any time its return value was not assigned to a char *.
So, it is very likely that Kernighan was doing it out of habit.

But there is another reason, mentioned in the preface:

We used Bjarne Stroustrup's C++ translator extensively for local
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^
testing of our programs, and Dave Kristol provided us with an ANSI
^^^^^^^^^^^^^^^ ^^^^^^^^
C compiler for final testing.

Since C++ requires the cast, the authors had no chance but to use it.


Dennis Ritchie and Brian Kernighan are among the most thoughtful of
people. They did have a choice at the time. If they had thought it
important/best to leave malloc calls uncast they could have (1) used
the ANSI C compiler or (2) edited the casts out in the final draft
(after the final check with the ANSI C compiler) or (3) politely asked
me for a compatibility feature in Cfront (we talked almost every day).

I think it is safest to assume that when Dennis Ritchie and Brian
Kernighan did something, it was because they wanted to do that and not
the opposite.


They officially "repented" for doing it. See the K&R2 errata at
http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

142(§6.5, toward the end): 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.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #167
Bjarne Stroustrup <bs@research.at t.com> scribbled the following:
Dennis Ritchie and Brian Kernighan are among the most thoughtful of
people. They did have a choice at the time. If they had thought it
important/best to leave malloc calls uncast they could have (1) used
the ANSI C compiler or (2) edited the casts out in the final draft
(after the final check with the ANSI C compiler) or (3) politely asked
me for a compatibility feature in Cfront (we talked almost every day). I think it is safest to assume that when Dennis Ritchie and Brian
Kernighan did something, it was because they wanted to do that and not
the opposite.


At the risk of sounding like an idiot, I have to ask you what you mean
by "the opposite". Do you mean that Ritchie and Kernighan did <X>
because they wanted to do <X> instead of the opposite of <X>? Or do
you mean that they did something because they wanted to do it, not
because they didn't want to do it?

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Roses are red, violets are blue, I'm a schitzophrenic and so am I."
- Bob Wiley
Nov 14 '05 #168
"P.J. Plauger" <pj*@dinkumware .com> wrote:
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:40******** ********@news.i ndividual.net.. .
"P.J. Plauger" <pj*@dinkumware .com> wrote:
If you write malloc calls without casts, it's not because it's
necessarily good programming practice but because your grandfather did.
I would find it slightly insulting that an otherwise respectable
programmer like yourself would assume that I hadn't actually thought
about the matter, if it hadn't been you and this particular dispute.


Sorry, I was being cute at the cost of some precision. And I certainly
didn't intend to be insulting with that statement


I know you didn't. That's one reason why, it coming from you, I wasn't
insulted.
My point was that you *can* write malloc calls
without casts only because the C committee gave them special
dispensation.


But this isn't true! You can write malloc() calls without casts because
malloc() returns void *. Now, void pointers have special dispensation
from needing casts; but this has nothing specifically to do with
malloc(). It's a general property of void *s, also often used in qsort()
callback functions, for example.
As it is, I'll just state, flatly, that you're bloody wrong.


I have trouble feeling wrong when I'm trying to state a more
ecumenical position than damn near anybody else in this thread.


Your ecumenicality on casts has nothing to do with the above sentence;
you are simply provably wrong on _my_ position on casts, which is a
level of opinionatedness extra :-).
IOW, regardless of which of us is right about casts, you're wrong about
_me_.
avoid casts as much as possible, and I _do_ think that that is
necessarily good programming practice, and neither of my grandfathers
programmed, so I formed my own opinion on this.


It's fine with me if you adopt this style, particularly having thought
it through. It's less fine that you and others absolutely refuse to
let in the possibility that well meaning people might arrive at a
different conclusion on such a delicate matter of style.


Ah, well, you see, that's because I've ever only heard of three
arguments for the cast, and several against; and those against are of
higher quality than those for.

For the casts, we have "I have customers who need to compile this on all
kinds of compilers, and I cannot hand-gear my code for every single
situation" (you, and AFAICT, nobody else); "But it breaks when I compile
my C code on my C++ compiler!!!" (all newbies in the world, seemingly,
and Tisdale); and "The code with the cast is more solid and type-safe"
(several kinds of trolls and confused newbies).
The first argument, yours, holds some water, but only in exceptional
circumstances. Now, _you_, in fact, are in exceptional circumstances,
being an implementation writer and creator of code for others, so this
argument holds water for you. I don't think I've ever seen anyone else
in c.l.c to whom it applies, though.
To the second argument, one need only say "Well, don't do that, then",
just as to people who complain that their C code won't compile as Java.
As for the third argument, it is demonstrably false; and has been shown
to be false repeatedly in this newsgroup.
If you know of any other argument _for_ the casts, one which applies to
your average programmer and not just to someone who, like you, has
special requirements, and one which actually stands the test of c.l.c,
I'd love to hear it.

Against casting malloc(), we have several arguments, ranging from
shorter typing and less cluttered code, through the demonstration that
code without the cast, written properly, is actually _more_ solid than
code with it, to my own more philosophical argument that _any_ warning
sign is bad when over-used, because it devaluates the warning where it
is necessary; the "cry wolf" argument. All of those have been argued
more than once (or twice, or a thousand times) here; I have never seen
any of them properly refuted.

In the end, then, we may come across as somewhat curt, sometimes; but
that is because all these arguments have already been brought forward,
they're now just being re-hashed over and over again, and we've all
already made up our minds, in a perfectly rational way, a long time ago.
And each time Mr. Tisdale, or someone else, pulls out yet another
re-statement of the same tired old "but C is just C++ stripped down, and
I want to compile C as C++", we, at least I, do get just a little weary.
But that doesn't mean we haven't thought about it. We _have_, over and
over again; that's the reason.

Richard
Nov 14 '05 #169
On Wed, 28 Jan 2004, Richard Bos wrote:
As for the third argument, it is demonstrably false; and has been shown
to be false repeatedly in this newsgroup.


AFAICT it has /not/ been shown false. The lack of malloc
casts could actually hide undefined behaviors:

#include <stdio.h>
#include <stdlib.h>

double *x; /* Wrong declaration */

int
main(void)
{
x = (int *) malloc(sizeof *x);
if (x) {
*x = 4;
printf("%d\n", *x); /* Undefined behavior */
free(x);
}
return 0;
}

With the malloc cast, you are guaranteed a diagnostic.
Without the cast, the diagnostic is not required. Bad style
perhaps, but this possibility should not be dismissed.

Tak-Shing

Nov 14 '05 #170

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
2303
by: hermit_crab67 | last post by:
Can someone explain to a C newbie why this doesn't work as I expect it to work? (expectations clearly outlined in the printf statement in main routine) OS: Linux 2.4.26 GCC: 2.95.4 void modify_pointer(char *); int main(int argc, char *argv) {
35
2726
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
32
2405
by: alex.j.k2 | last post by:
Hello all, I have "PRECISION" defined in the preprocessor code and it could be int, float or double, but I do not know in the code what it is. Now if I want to assign zero to a "PRECISION" variable, which of the following lines are correct:
101
4389
by: Tinkertim | last post by:
Hi, I have often wondered if casting the return value of malloc() (or friends) actually helps anything, recent threads here suggest that it does not .. so I hope to find out. For instance : char *tmp = NULL;
0
9969
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
11203
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10896
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10443
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9612
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
7151
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
6029
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4650
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3257
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.