473,854 Members | 1,476 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 23330
On Mon, 26 Jan 2004 21:55:49 GMT, in comp.lang.c , Default User
<fi********@boe ing.com.invalid > wrote:
pete wrote:

You do realise that it's a function of whether the roll
is above or below your elbow, and not a universal constant,
don't you ?


If it's the kind with jokes printed on the roll, then it needs to come
over the top so it will be readable.


Depends what position you adopt when using the facilities....
=:-0

--
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 #131
"P.J. Plauger" wrote:

"j" <ja**********@b ellsouth.net> wrote in message
news:Lp******** *******@bignews 3.bellsouth.net ...
1) Given that casts from malloc _are_ superfluous, why should one
cast?


Given that most whitespace _is_ superfluous, why should one use
whitespace?

How are casts from malloc() superfluous? Code should work identically
whether the casts are there or not. However, code that uses casts is
different from that which does not in cases of failure to properly
declare malloc(). In that case they convert a int into a pointer.

Brian Rodenborn
Nov 14 '05 #132
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:mi******** *************** *********@4ax.c om...
On Mon, 26 Jan 2004 00:29:24 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
What I find interesting about this debate is the two positions being
espoused:


Correct. But not these two. The two positions are

1) putting in malloc casts is perfectly ok, its harmless.
2) putting in malloc casts is unnecessary and therefore not ok.


I'm beginning to understand the communication problem here.
I've never espoused either of these posiitons, but that seems
to be what you've read.
Those of us in the first camp are going to keep using casts,


But you're not in that camp. Youre in the "casting malloc is a good
thing" camp, as your own postings both in this thread and elsewhere
have showed.


Not to me.
and we're
going to keep respecting those who don't. It would be nice if we were
granted a bit of respect in turn, but what the hell.


As I said, I respect you enormously. You mistake intolerance of your
one stupidity for lack of respect


Uh yes, I *do* consider intolerance a lack of respect. Fortunately for
me, I don't really give a rat's ass whether you respect me or not.
I've been staying in this discussion for a variety of tutorial
purposes (which IMO I've been achieving).
A closed mind avoids the risk of having to change.


I'd not know, I don't have one.


And yet you can be intolerant. An interesting pair of positions
to reconcile.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #133
"Default User" <fi********@boe ing.com.invalid > wrote in message
news:40******** *******@boeing. com.invalid...
"P.J. Plauger" wrote:

"j" <ja**********@b ellsouth.net> wrote in message
news:Lp******** *******@bignews 3.bellsouth.net ...
1) Given that casts from malloc _are_ superfluous, why should one
cast?
Given that most whitespace _is_ superfluous, why should one use
whitespace?

How are casts from malloc() superfluous? Code should work identically
whether the casts are there or not.


I personally never said that casts from malloc() are superfluous,
just whitespace. And how code "should work" is just one factor to
consider in developing style rules.
However, code that uses casts is
different from that which does not in cases of failure to properly
declare malloc(). In that case they convert a int into a pointer.


Right. And other failures are caught when casts *are* present that
are obscured when they're omitted. It's a tradeoff, a matter of
choosing relative weights. Once you decide that any one weight is
a binary choice between okay and idiocy, you may as well divide
through by zero.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #134
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:eb******** *************** *********@4ax.c om...
On Mon, 26 Jan 2004 22:54:26 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
"j" <ja**********@b ellsouth.net> wrote in message
news:Lp******* ********@bignew s3.bellsouth.ne t...
1) Given that casts from malloc _are_ superfluous, why should one
cast?


Given that most whitespace _is_ superfluous, why should one use
whitespace?


Igenerallydon't whenitdoesn'tma tter-haveyoueverseen webbytheway?

Joking aside, you're actually reinforcing one of the arguments against
casting. One should write for readability. Whitespace (used
approriately) improves that. Casts (used appropriately) improve that.
Casts stuck in where unnecessary do not improve that.


Again you're applying one set of weights and value judgements with
nary a thought that other weights might be valid in other contexts.
Ever think of becoming a defense lawyer? You certainly like to stack the
deck against any answers you don't want to hear.


This statement has a fine legal name, which escapes me for the moment.
Its something to do with trying to divert attention off the actual
point, because you don't have a rebuttal.


Well, maybe. Had I stopped there, you might have a legitimate gripe.
But the part you snipped went on to discuss the various answers I've
given.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #135
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:qs******** *************** *********@4ax.c om...
On 26 Jan 2004 21:11:41 GMT, in comp.lang.c , mw*****@newsguy .com
(Michael Wojcik) wrote:
I suspect Mark thought you were claiming that a (non-null) void *
value *returned by malloc* could point to an area that was
incorrectly aligned for double.


Yes, since this was the topic under discussion !
I also suspect Mark did not recognize your name, or he might have
double-checked before posting


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. From your earlier posting:

: This statement has a fine legal name, which escapes me for the moment.
: Its something to do with trying to divert attention off the actual
: point, because you don't have a rebuttal.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com


Nov 14 '05 #136
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:dl******** *************** *********@4ax.c om...
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. It is no longer amusing that you keep calling
my position idiotic; now it is merely sad. My part of this discussion
is nearing its end. (And you accuse others of trolling...)
He has already stated for the benefit of this newsgroup that
(what I consider to be) his unusual circumstances
make it sensible for him to make his code capable
of being compiled under both C and C++; given his reputation,


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. I've merely been defending
why it might sometimes be a reasonable position for some C
programmers in some contexts. The only thing I really can't stand
is intolerance. But you can only push that button of mine so many
times before I learn to tune it out.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #137
Christian Bau wrote:
If we go into things that are not C, then why not

allocate (p, 1);

with a new library function "allocate" which takes two arguments: An
lvalue p which must be a pointer to a complete type, and an integer. The
function would allocate space for as many objects as the integer
specifies and store the result in the pointer variable.

No chance to cast anything, so the whole argument would go away :-)


No. Pointer p could never be a constant.

Nov 14 '05 #138
E. Robert Tisdale wrote:
Christian Bau wrote:
If we go into things that are not C, then why not

allocate (p, 1);

with a new library function "allocate" which takes two arguments: An
lvalue p which must be a pointer to a complete type, and an integer. The
function would allocate space for as many objects as the integer
specifies and store the result in the pointer variable.

No chance to cast anything, so the whole argument would go away :-)


No. Pointer p could never be a constant.


With one exception, each word on the first line of Christian's reply is
monosyllabic. How on /earth/ did you manage to misunderstand it?
--
Richard Heathfield : bi****@eton.pow ernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #139
Mark A. Odell wrote:
Sidney Cadot <si****@jigsaw. nl> wrote in
news:bu******** **@news.tudelft .nl:

If the FAQ is to properly reflect the CLC opinion, it should at least
mention the counter-argument that failing to cast malloc prevents a C++
compiler from having a fighting chance at compiling your code.
Why would a C++ compiler need to worry about malloc()'ing code?
To be compliant with the relevant standard, ISO 14882.
They have memory allocation schemes of their own in C++.
So they do, but in addition, malloc(), free(), and friends are also
supported, with semantics that are pretty close to C semantics. No
points for guessing why that is.
All my loop indexes are called 'new' just to prevent accidental
C++ compilation C code (okay, not really).
I fail to see your point.
At least, the presentation of the issue would then be honest. Right now,
it is an over-simplification of a complicated issue where there are
really two sides, I think.

No, two languages. One that has malloc() and does not require a cast and a
language that cannot prohibit the use of the former's memory allocation
function but that does require a cast.


Let me get this straight: do you deny there are to sides to this issue?
This seems to be somewhat implied by the "No".

Yours may well be bigger than mine, but surely, there /are/ two sides.

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, I see perfectly
well the limitations of my view and see the good sense in some of the
arguments of those I disagree with. In fact, when commenting on code
that does malloc casting here in c.l.c., I have repeatedly pointed out
that malloc casting is generally not considered good style by most
regulars. A minimal amount of reciprocity would be welcome.

Best regards,

Sidney

Nov 14 '05 #140

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

Similar topics

33
2300
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
2721
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
2403
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
4381
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
9901
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
10685
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10763
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
10371
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
9518
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...
1
7918
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7082
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();...
1
4563
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
3188
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.