473,854 Members | 1,531 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 23326
In article <40************ **@jpl.nasa.gov >,
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote:
That's an 'Ad Hominen' argument:

http://www.don-lindsay-archive.org/s...s.html#hominem

Whether P. J. Plauger is complete or incomplete idiot
has no bearing upon whether he is correct or not. :-)

Stupid people use fallacious arguments to persuade other stupid people.
Your personal attack on P. J. Plauger is a clear signal
to all subscribers that you have lost your argument
and descended to name calling instead of withdrawing graciously.


Tisdale, you shouldn't get involved in a discussion between adults, even
when these adults don't behave as if they are adults.

Considering your history of trolling, forging posts, giving ridiculous
advice to newcomers, any moral judgment coming from you is deeply
unappreciated.
Nov 14 '05 #71
Brian Blais wrote:
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


I' ve read nearly completely the whole thread, although in the way I
lost my path.

I assume the following:

d = malloc(50*sizeo f(*d));
--------------------------
o the sortest way
o the most portable
o does remember you to include stdlib
o changing type of d does not affect anything
o it looks a bit funny

d = malloc(50*sizeo f(double));
------------------------------
o changing type of d is disastrous

d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not want stdlib (but aren't all pointers unsigned ints? - enlight
me plz)
o it gives a good hint on what d's type is
ï if you change d's type it tells you so

Am I missing anything else???

Nov 14 '05 #72
Richard Heathfield wrote:
If you're wise, Mark, you'll retract that.
Mr. Plauger's statement, quoted above, is IMHO erroneous
but I don't think it's legitimate to call him an idiot.

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,
Please note that P. J. Plauger *never* "pulled rank" on you.
As far as I'm concerned Mr. Plauger is just another subscriber
to the comp.lang.c newsgroup. I find his argument compelling
because it is sound and *not* because of his "reputation ".
it makes sense to take him at his word
(although that does not necessarily mean that it's sensible
to emulate him blindly, in this case; we're not /all/
writing standard libraries for C and C++ compilers, after all).
I don't think that
Mr. Plauuger ever argued hardship or special circumstances.
I am not forced into the position of choosing
which of you is right about malloc (for I have my own opinion on that,
and I like to think that it's an informed opinion);
and thank heaven for that,
when both sides are using words like "idiot" and "nonsense".
I dread to think what must be going through the newbies' heads
as they read your exchange with Mr Plauger.


New subscribers should note that style issues
are the most contentious issues argued in the comp.lang.c newsgroup.

Nov 14 '05 #73
Papadopoulos Giannis wrote:


I' ve read nearly completely the whole thread
although in the way I lost my path.

I assume the following:

d = malloc(50*sizeo f(*d));
--------------------------
o the shortest way
o the most portable
o does remember you to include stdlib
No. It does *not* remind you to include stdlib.
The best that you can expect is that your compiler
will issue a diagnostic:

warning: implicit declaration of function `malloc'
o changing type of d does not affect anything
o it looks a bit funny

d = malloc(50*sizeo f(double));
------------------------------
o changing type of d is disastrous

d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not warn stdlib
A good C compiler will tell you that

warning: implicit declaration of function `malloc'
(but aren't all pointers unsigned ints? - enlight me plz)
No.
o it gives a good hint on what d's type is
So would

double* d = (double*)malloc (50*sizeof(doub le));
ï if you change d's type it tells you so

Am I missing anything else?

Nov 14 '05 #74
E. Robert Tisdale wrote:
(but aren't all pointers unsigned ints? - enlight me plz)

No.


So???
o it gives a good hint on what d's type is

So would

double* d = (double*)malloc (50*sizeof(doub le));


I think I wrote it first :) - though, without the leading double* which
is implied indeed...

Nov 14 '05 #75
"Mark Bruno" <ya************ *@yahoo.com> wrote:

[ Imprimis, while snipping is good, snipping every single bit of context
is not. ]
Stroutstrup himself has said that all good-style C programs are also C++
programs,
Well, he's just wrong, then, isn't he? Or rather, he has what I would
consider silly opinions about what is good style in C; good style in C
does _not_ involve useless casts strewn through your code.
so it's just better style.
Let me get this right: someone who is an authority on C++ says something
about C, _so_ it is correct? Don't you think you trust big names a bit
too easily?
Also, we're not limited to malloc() here,
One more reason not to care what a C++ compiler does with C code.
Thirdly, it's always best to be explicit.
Wrong.

Or do you also write

(void) (int_a = (int) int_b);

and

for (i=(size_t)0;
(size_t)i<(size _t)NUMENTRIES;
i=(size_t)((siz e_t)i+(size_t)1 ))
if ((int)mung_arra y((int *)array, (size_t)i)!=(in t)0)
break;
Lastly, it provides compatibility with older compilers.


Which, for the average user, is the only reason, and it is one that
should come up rarely, if ever.

OTOH, too many casts engender confusion in the programmer and insecurity
in the maintainer, so they are an abomination.

Richard
Nov 14 '05 #76
Papadopoulos Giannis <ip******@inf.u th.gr> scribbled the following:
I' ve read nearly completely the whole thread, although in the way I
lost my path. I assume the following: d = malloc(50*sizeo f(*d));
--------------------------
o the sortest way
Well, the shortest way would be d = malloc(50*sizeo f *d), but you're
otherwise right.
o the most portable
o does remember you to include stdlib
o changing type of d does not affect anything
Yes.
o it looks a bit funny
That's a matter of taste.
d = malloc(50*sizeo f(double));
------------------------------
o changing type of d is disastrous
Right.
d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not want stdlib (but aren't all pointers unsigned ints? - enlight
me plz)
This is not true at all. Pointers and unsigned ints are entirely
different beasts. They aren't even required to have the same size!
And even if they have the same size, they might be coming from
different places, for example different data transfer registers.
Note that casting the return value of malloc() *ONLY* shuts up
compiler warnings. It *DOES NOT* fix the code.
Read carefully, because this is important:
*** THE - CODE - IS - STILL - BROKEN!!! ***
o it gives a good hint on what d's type is
ï if you change d's type it tells you so
True, but as the code is broken anyway, this is irrelevant.
Am I missing anything else???


No, that's basically it.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The truth is out there, man! Way out there!"
- Professor Ashfield
Nov 14 '05 #77
In article <bv***********@ ulysses.noc.ntu a.gr>,
Papadopoulos Giannis <ip******@inf.u th.gr> wrote:
Am I missing anything else???


The only thing that is missing is that many good programmers try to
avoid any unnecessary cast if at all possible:

A cast tells the compiler "Shut up, I know what I am doing". In reality
it means "Shut up, I thought I knew what I was doing when I wrote this,
even though I might have been wrong at the time or things might have
changed and nowadays the code might be completely wrong".

For example, your program might contain an extern function

int nalloc (double x);

Maybe not very clever to have a function with a name very similar to
malloc, but you might have a completely good reason to use that function
name. Suppose this function does something completely different than
malloc, and suppose you type the malloc call wrong:

double* d = nalloc (100 * sizeof (double)); // Error
double* d = (double *) nalloc (100 * sizeof (double)); // No error

So many people have the habit of _never_ using casts if they can be
avoided.
Nov 14 '05 #78
Joona I Palaste wrote:
Papadopoulos Giannis <ip******@inf.u th.gr> scribbled the following:
d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not want stdlib (but aren't all pointers unsigned ints? - enlight
me plz)

This is not true at all. Pointers and unsigned ints are entirely
different beasts. They aren't even required to have the same size!
And even if they have the same size, they might be coming from
different places, for example different data transfer registers.
Note that casting the return value of malloc() *ONLY* shuts up
compiler warnings. It *DOES NOT* fix the code.
Read carefully, because this is important:
*** THE - CODE - IS - STILL - BROKEN!!! ***


I got confused by the older C spec... Sorry...

As for the

d = (double*)malloc ( 50*sizeof(doubl e) );

d is double*...
But if I want to make illegal actions, casting is the best... ;)

Tnx anyway

Nov 14 '05 #79
In article <40************ ****@news.indiv idual.net>,
rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote:
OTOH, too many casts engender confusion in the programmer and insecurity
in the maintainer, so they are an abomination.


Usually goes like this:

"This cast looks useless to me. No good programmer would use useless
casts. I assume that the original author was a good programmer, so he
wouldn't use useless casts, so the cast is not useless. So what is this
damned cast doing that I cannot figure out? "

And now we have a maintenance programmer wasting time to figure out what
a useless cast is good for, because he made the (incorrect) assumption
that the author knew what he was doing...
Nov 14 '05 #80

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
9751
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
11027
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
10682
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...
0
9513
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
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();...
0
5743
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
4159
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3187
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.