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
Richard Bos wrote:
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..

Hey, I'm not disputing your choice, only the denomination "shortest". If
you want to write ugly code, be my guest :-)


Ugly style or not, I got used to it and it is really difficult to adopt
a new style...

Anyone who does not like my code, has always the choice of a
beautifier... And I don't think it's all that bad...

Nov 14 '05 #111
Papadopoulos Giannis <ip******@inf.u th.gr> scribbled the following:
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..


Then *why* do you use parantheses in return statements? To make return
look like a function, so you can snigger when newbies think it really
*is* a function? =)

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"It sure is cool having money and chicks."
- Beavis and Butt-head
Nov 14 '05 #112
:::: 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.

Let me get this strait.

"Your lack of cast on malloc is traditional,
not a superior programming technique"
and
"You are an idiot"

are considered equally ad hominem. Good to know, good to know.

In the meanwhile, perhaps it isn't too horrible to point out that
adding the cast is duplicated information, (which you might think
is bad, but) which means static checking can diagnose some problems
otherwise difficult to find, and often having to do with writing
past the end of the malloced region, which is Bad, which makes
the apparently bad duplication Good.

To a certain extent, it's a matter of style, but I find that
putting assertions and "redundant" casts in code makes it
significantly more likely to work if it compiles.
Therefore I find this a *useful* style.

But that's just me, and I must say I sympathize with stating
the same type twice (once for size (which is sometimes implicit),
once for typechecking) in the same malloc call.

On the Nth hand, something like

p = malloc(sizeof *p);

is particularly handy, because you can change the type of p
without having to dive into the code everywhere. Better (IMO)
would be something like

p = (typeof *p)malloc(sizeo f *p);

but I don't think that works.
Wayne Throop th*****@sheol.o rg http://sheol.org/throopw
Nov 14 '05 #113
Wayne Throop <th*****@sheol. org> scribbled the following:

(snip discussion about Trollsdale and PJ Plauger)
In the meanwhile, perhaps it isn't too horrible to point out that
adding the cast is duplicated information, (which you might think
is bad, but) which means static checking can diagnose some problems
otherwise difficult to find, and often having to do with writing
past the end of the malloced region, which is Bad, which makes
the apparently bad duplication Good.
Yes, I agree, but the advantage of *not* casting is that the compiler
warns you about an incorrectly prototyped malloc(), which is a really
serious error, and one which no amount of casting anywhere can fix.
This, in my opinion, *far* outweighs any potential gain you might get
from the static checking you above describe. After all, if the returned
pointer is garbage right from the start, all bounds checking is
completely moot.
On the Nth hand, something like p = malloc(sizeof *p); is particularly handy, because you can change the type of p
without having to dive into the code everywhere. Better (IMO)
would be something like p = (typeof *p)malloc(sizeo f *p); but I don't think that works.


No, that doesn't work, not in C anyway.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Remember: There are only three kinds of people - those who can count and those
who can't."
- Vampyra
Nov 14 '05 #114
P.J. Plauger wrote:
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.


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 ?

--
pete
Nov 14 '05 #115

In article <8_************ ********@comcas t.com>, "Mark Bruno" <ya************ *@yahoo.com> writes:
Stroutstrup himself has said that all good-style C programs are also C++
programs, so it's just better style.
I am continually amazed at people who think Stroustrop (I assume this
is whom you meant) magically gets the last word in this argument. He
clearly has an interest in promoting C++, and that very likely
includes persuading C programmers to switch. What makes you think
he's an impartial observer? For that matter, what makes you think
he's right?

I have just invented a new language, called "C2", which is exactly
like C89 except that all identifiers must be at least 2 characters,
because I don't like single-character identifiers. All "good-style C
programs" are also C2 programs, which proves that 1) C2 is a "better
C", and 2) that avoiding single-character identifiers is "just better
style".

No, you say? Why is this argument valid for Stroustrop and not for
me?
Also, we're not limited to malloc()
here, what if you wrote your own function that returns a generic pointer.
What if I did? The same argument (against casting its return value)
would appear to apply.
Thirdly, it's always best to be explicit.
Why?
Lastly, it provides compatibility with older compilers.


I suspect a very small subset of C programmers need to write code
which is acceptable to both C89 and pre-C89 implementations , or
indeed write for pre-C89 implementations at all. Those who do may
indeed need to cast malloc. Their situation is not the common one,
nor the one we assume on this newsgroup, which is intended for the
discussion of standard C.

--
Michael Wojcik mi************@ microfocus.com

What is it with this warm, quiet, nauseating bond between them?
-- Rumiko Takahashi, _Maison Ikkoku_, trans. Mari Morimoto, adapt. Gerard
Jones
Nov 14 '05 #116
Michael Wojcik <mw*****@newsgu y.com> scribbled the following:
In article <8_************ ********@comcas t.com>, "Mark Bruno" <ya************ *@yahoo.com> writes:
Stroutstrup himself has said that all good-style C programs are also C++
programs, so it's just better style.
I am continually amazed at people who think Stroustrop (I assume this
is whom you meant) magically gets the last word in this argument. He
clearly has an interest in promoting C++, and that very likely
includes persuading C programmers to switch. What makes you think
he's an impartial observer? For that matter, what makes you think
he's right? I have just invented a new language, called "C2", which is exactly
like C89 except that all identifiers must be at least 2 characters,
because I don't like single-character identifiers. All "good-style C
programs" are also C2 programs, which proves that 1) C2 is a "better
C", and 2) that avoiding single-character identifiers is "just better
style". No, you say? Why is this argument valid for Stroustrop and not for
me?


You are right. Stroustrup's opinion matters on C++, and your opinion
matters on C2, but neither of your (neither's of you?) opinion matters
on C. C++ is Stroustrup's language and C2 is yours, fine, you can keep
them. Neither of you has claim over C.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"My absolute aspect is probably..."
- Mato Valtonen
Nov 14 '05 #117

In article <hq************ *****@nwrddc01. gnilink.net>, "P.J. Plauger" <pj*@dinkumware .com> writes:
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:sv******** *************** *********@4ax.c om...
On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
"Jack Klein" <ja*******@spam cop.net> wrote in message
news:c2******* *************** **********@4ax. com...

> > warning: invalid conversion from `void*' to `double*'
>
> This is comp.lang.c, there is no such thing as an invalid conversion
> from void* to double*. The conversion is implicit and correct.

If the alignment is incorrect the conversion is invalid.


But its impossible for it to be incorrect. The C Standard says so. If
your h/w platform can't guarantee it, then you can't implement C
there.


Next step after nonsense -- bullshit. See 6.3.2.3, para. 7.


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. Of course a void * value obtained
another way (from the address of a pointer to a different type, or
from an uninitialized automatic void* variable, and so forth) may
point to such an area, and assigning such a value to a double* would
be invalid.

I also suspect Mark did not recognize your name, or he might have
double-checked before posting.

Of course, my suspicions may be ill-founded.

--
Michael Wojcik mi************@ microfocus.com

Do not "test" parts, as this may compromise sensitive joinery. Those who
suffer difficulty should abandon the enterprise immediately. -- Chris Ware
Nov 14 '05 #118
pete wrote:
P.J. Plauger wrote:
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.


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 ?


The universal solution, not approved by some style mavens, is to
remove the roll from the dispenser and leave it on the tank. :-)
This makes it fairly easy to perform the necessary allocations.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 14 '05 #119
In article <10********@she ol.org>, th*****@sheol.o rg (Wayne Throop)
wrote:
On the Nth hand, something like

p = malloc(sizeof *p);

is particularly handy, because you can change the type of p
without having to dive into the code everywhere. Better (IMO)
would be something like

p = (typeof *p)malloc(sizeo f *p);

but I don't think that works.


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 :-)

(Even better if this comes together with a reallocate function that
returns a boolean upon success; using realloc is always a pain. )
Nov 14 '05 #120

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
9752
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
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...
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();...
0
5750
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...
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.