473,839 Members | 1,485 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 23297
"pete" <pf*****@mindsp ring.com> wrote in message
news:40******** ***@mindspring. com...
Richard Bos wrote:

"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote:
Mark McIntyre wrote:

> P.J. Plauger wrote:
>
>>If you write malloc calls without casts, it's not because it's
>>necessarily good programming practice
>>but because your grandfather did. But this is the one place where you're an idiot. A complete one.

That's an 'Ad Hominen' argument:
So is Plauger's assertion that those of us who disagree with him do so
out of mere tradition.


Especially since original K&R C used the cast.
The cast is the old way. No cast, is the new way.


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.

Great quantities of code existed without casts on malloc calls.
We knew that people would object violently to being forced to
go through all that code and decorate all mslloc calls with casts.
Of course, there were also great quantities of code that didn't
include all necessary headers to get library functions properly
declared (in many cases relying on representation punning between
default int return types and pointers), but it's way easier to
fixup an old source file by adding a few includes.

So it's both simplistic and incorrect to assert:
The cast is the old way. No cast, is the new way.


Four legs good, two legs bad.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #101
P.J. Plauger wrote:

"pete" <pf*****@mindsp ring.com> wrote in message
news:40******** ***@mindspring. com...

The cast is the old way. No cast, is the new way.


Four legs good, two legs bad.


Four legs animal. Two legs man.

--
pete
Nov 14 '05 #102
"pete" <pf*****@mindsp ring.com> wrote in message
news:40******** ***@mindspring. com...
P.J. Plauger wrote:

"pete" <pf*****@mindsp ring.com> wrote in message
news:40******** ***@mindspring. com...

The cast is the old way. No cast, is the new way.


Four legs good, two legs bad.


Four legs animal. Two legs man.


Really? Remember the ancient riddle: what walks on four legs in
the morning, two legs in the afternoon, and three legs in the
evening?

Few things are as simple as they at first appear.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #103
P.J. Plauger wrote:
"pete" <pf*****@mindsp ring.com> wrote in message
news:40******** ***@mindspring. com...
P.J. Plauger wrote:
>
> "pete" <pf*****@mindsp ring.com> wrote in message
> news:40******** ***@mindspring. com...
> > The cast is the old way. No cast, is the new way.
>
> Four legs good, two legs bad.


Four legs animal. Two legs man.


Really? Remember the ancient riddle: what walks on four legs in
the morning, two legs in the afternoon, and three legs in the
evening?


A fish!

Few things are as simple as they at first appear.


This is certainly true of the whole malloc thing. I must admit I had no idea
that In The Beginning, malloc casts were not required. (That doesn't change
my opinion that it is unwise - in the main! - for C programmers to provide
the cast.)

--
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 #104
xarax wrote:

"Default User" <fi********@boe ing.com.invalid > wrote in message
news:40******** *******@boeing. com.invalid...

You shouldn't be using malloc() in C++ period. Writing code to move back
and forth like that is poor idea. C++ is its own language, and you
should be writing C++ code using the modern libraries. Don't write
cripple C code for C++ applications.


I interpreted his remark as *not* writing code
that compiles for both C and C++, but that he
doesn't have to change his *style* for either
language.

But you don't cast the result from new in C++, so the "style" is more
consistent not to do that for C either.

At any rate, substance over style says not to cast in C, because it can
hide defects in the code. It can't for C++.

Brian Rodenborn
Nov 14 '05 #105
Richard Heathfield wrote:
And I never said that he did. It is I who respect his reputation, not he who
insists on being respected.

That's a foreign concept to Mr. Tisdale, as he has never experienced
respect for his reputation.


Brian Rodenborn
Nov 14 '05 #106
"P.J. Plauger" wrote:
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.

For many of use, the decision on correctness here comes from experience.
We see a LOT of newbie code, and a common error is to omit the inclusion
of stdlib.h and have that covered up with a cast. Sometimes the cast was
made deliberately to make the compiler shut up.

Now yes, the chances of that happening to an experienced programmer are
slim. Trollsdale will claim it's not a problem because his compiler
warns him about the missing include, and yes most compilers will or can
be set to issue such warnings, but we see the evidence. New programmer
DON'T have their compilers set. And they DO forget the include.

I'm of the opinion like many here that it's cleaner, it's more likely to
be correct, and who cares about C++ anyway? When I'm writing C++, I'll
worry about C++ish things. When I'm writing C, I'll worry about Cish
things.

There may be some people writing common source code libraries, but
that's not most of us, and such people aren't learning to program
anyway. They are also well plugged into the commonalities and
differences between the languages. That doesn't drive a general rule for
all C programmers.


Brian Rodenborn
Nov 14 '05 #107
j

"P.J. Plauger" <pj*@dinkumware .com> wrote in message
news:aC******** ********@nwrddc 01.gnilink.net. ..
"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 (or the rationale
that preceded it). My point was that you *can* write malloc calls
without casts only because the C committee gave them special
dispensation. We adopted a stronger typing system than in traditional
C with malice aforethought, but we didn't want to force the rewrite
of gazillions of lines of code that had been written without casts.
That would have been the result of adopting the tidier and more
consistent type-conversion rules of C++. We understood that malloc
calls were safer than average, because of the extra semantic
constraints imposed on the object pointers it returns; but we still
created a funny hole that's troublesome in other contexts, and we still
created a gratuitous difference between C and C++. Perhaps we should
have used some other notation in this context, instead of pirating
C++ notation and perverting it. But we did what we did.
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.


I don't think that you are, considering your original replies to both
Jack Klein and Mark McIntyre.

Or to be more succinct: "Nonsense! Bullshit!"
I _do_
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.


1) Given that casts from malloc _are_ superfluous, why should one
cast?(Reference s to languages other than ISO C are off-topic for this
newsgroup
e.g., ``I do so because I program in C++ at work, so I have adopted this
habit''
-- what you do at work is really irrelevant for this newsgroup, i.e., ERT's
original post)

2) Why should one cast from malloc when it might suppress a warning
which might otherwise be useful? (We all forget to include headers from
time to time)

I had a roommate in college whom I had known through most of high
school. He was a bright guy (got consistently better grades than
me) and we mostly got along. But early in our cohabitation, I
discovered that he put a toilet paper roll on the dispenser
backwards from the way I did. Now I had carefully thought through
the matter and worked out which was the right way. Yet this otherwise
intelligent guy had done the same exercise and came up with the
WRONG conclusion. We eventually worked out our differences without
bloodsheed.

The amusing thing about this story is that, for the past thirty
years, I have been unable to recall what MY original position was
or what OUR compromise became. And that lapse doesn't keep me
awake nights.

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

Nov 14 '05 #108
In article <bv***********@ ulysses.noc.ntu a.gr>,
Papadopoulos Giannis <ip******@inf.u th.gr> wrote:
Richard Bos wrote:
d = malloc(50*sizeo f(*d));
--------------------------
o the sortest way

Nope. Lose the parens around *d, then it's the shortest.


I like 'em.. I also do return(EXIT_SUC CESS); :)
d = malloc(50*sizeo f(double));
------------------------------
o changing type of d is disastrous

Not for this single line, mind, but now imagine you have three dozen of
such lines in the program. You change a declaration, and all malloc()
calls. Except that you overlook one malloc()...


Implied...
(but aren't all pointers unsigned ints? - enlight me plz)

Certainly not. A pointer is a pointer, an integer is an integer. A
pointer to <foo> is an object suitable for containing the address of any
object of type <foo> - however the implementation chooses to implement
that address.
For example, in a debugging implementation, I can well imagine a pointer
consisting of the triplet <base memory block - start of object - size of
object>.


In the typical case I thought the pointer to be an int. I tried on win
and linux and managed to carry around a pointer in an int.

Unless, in other implementation a pointer is more than just an int..
Any more info??


64 bit Linux is getting quite popular.
Nov 14 '05 #109
Joona I Palaste wrote:
And I suppose you calculate the sum of an array this way?

int ar[(10)];
int i, sum=(0);
for ((i=(0)); ((i)<(10)); (i++)) {
(sum=((sum)+((a r)[(i)])));
}


Don't be so cynic... I do not think it is the same..

Nov 14 '05 #110

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

Similar topics

33
2295
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
2719
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
2399
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
4374
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
9854
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
9696
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10903
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...
0
10584
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
10645
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
9425
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
7015
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
4482
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
2
4063
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.