473,839 Members | 1,480 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
"Mark A. Odell" <no****@embedde dfw.com> wrote:
I always use the explicit cast
to prevent my C++ compiler from complaining about


You *shouldn't* use malloc in C++!


Why not? What if you wish to explictely make sure constructors are
not invoked for all entries? I don't think "new" has an option where
you can turn this off.
The important thing here is to adopt a style and stick to it.


True but this is not a style issue.


No, its a language weakness issue. One of the few good things to come
out of the C99 spec is the adoption of C++'s requirement for
prototype, and not assuming the default: int ()(int) . But since the
OP in highly unlikely to have practical access to a C99 compiler
within the next 5 years, the simpler solution is simply to compile
with C++ (after making your code C++ safe, of course) to catch these
and other kinds of errors.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 14 '05 #141
On 26 Jan 2004 21:23:19 GMT
Joona I Palaste <pa*****@cc.hel sinki.fi> wrote:
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.


I believe it's "neither of your opinions".

--
donLouis
Nov 14 '05 #142
Papadopoulos Giannis <ip******@inf.u th.gr> 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 sortest way
They all generate equivalent object code (when they are correct, and
as intended.)
o the most portable
Its not portable to anal C++ compilers set at their most pedantic
warning level.
o does remember you to include stdlib
Or malloc.h on some systems. However if you use a C++ (or C99)
compiler to compile your C code, you'll get the lack of prototype as
an error whether you cast or not.
o changing type of d does not affect anything
That is about its only real advantage.
d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not want stdlib (but aren't all pointers unsigned ints? - enlight
me plz)
On AMD64 (aka x86-64) pointers have long long (or __int64)
representation. On 16bit DOS systems pointers can have a kind of
int[2] representation. In general pointers should not be assumed to
be of size int on code which is supposed to be portable.
o it gives a good hint on what d's type is


Actually the declaration of d is the only credible source of what type
d is.

--
Paul Hsieh
http://www.pobox.com/~qed/
http://bstring.sf.net/
Nov 14 '05 #143
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.

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.

--
Allin Cottrell
Department of Economics
Wake Forest University, NC
Nov 14 '05 #144
Paul Hsieh wrote:
Papadopoulos Giannis <ip******@inf.u th.gr> wrote:
o does remember you to include stdlib
Or malloc.h on some systems.


<stdlib.h> is always correct for malloc.
<malloc.h> is rarely correct for malloc.
However if you use a C++ (or C99)
compiler to compile your C code, you'll get the lack of prototype as
an error whether you cast or not.


On C90 compilers, however, you won't; and C90 compilers are still the most
widely-used C compilers.
o changing type of d does not affect anything


That is about its only real advantage.


You forgot the other advantages to omitting the cast:

1) doesn't add pointless, unnecessary code;
2) doesn't suppress an important required diagnostic;
3) gives you a heads-up if you accidentally compile your C code with a
compiler for some other language with notionally similar syntax but
different semantics.
o it gives a good hint on what d's type is


Actually the declaration of d is the only credible source of what type
d is.


That's certainly true.

--
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 #145
In article <40************ **@jpl.nasa.gov >,
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > 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.


Go away, idiot.
Nov 14 '05 #146
th*****@sheol.o rg (Wayne Throop) wrote:

[ Please do not remove attribution lines. ]
:::: 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.
Yes. "You do not think when you don't cast malloc()" and "you do not
think when you do cast malloc()" are equally ad hominem.
After all, Mark didn't call Plauger an idiot per se, as you make him out
to have done; he quite specifically claimed that _this_ matter is the
only one where he considers him so.
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.


It doesn't work in C (though it might in Gnuck), it is probably wrong
anyway (shouldn't that be typeof p?), but most importantly: in what way
does it give you any more information at all than the first line? I see
absolutely no advantage to it whatsoever.

Richard
Nov 14 '05 #147
Richard Bos <rl*@hoekstra-uitgeverij.nl> scribbled the following:
th*****@sheol.o rg (Wayne Throop) wrote:
Better (IMO)
would be something like

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

but I don't think that works.
It doesn't work in C (though it might in Gnuck), it is probably wrong
anyway (shouldn't that be typeof p?), but most importantly: in what way
does it give you any more information at all than the first line? I see
absolutely no advantage to it whatsoever.


Well, it does have the advantage that if the type of p is ever changed,
then the compiler will... oh, sod that.
Well, it does have the advantage that if malloc() is incorrectly
prototyped, its return value will be... oh, sod that.
Well, it does have the advantage that it makes the code valid C++...
except C++ doesn't have a "typeof" operator.
Well, at least it does have the advantage of keeping people like
Trollsdale and PJ Plauger happy when they see that the cast is in
there. =)

--
/-- 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 #148
Default User <fi********@boe ing.com.invalid > wrote:
"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.


Yes. Which is why they're superfluous.
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.


Erm... no. They convert something the programmer _thinks_ is a pointer,
but has implicitly _declared_ to be an int, and which may not actually
exist or have a valid value, into a pointer. Without so much as a
warning.

Richard
Nov 14 '05 #149
"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:
"Jack Klein" <ja*******@spam cop.net> wrote in message
news:c2******** *************** *********@4ax.c om...

> > 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.

Nonsense. If the alignment is incorrect the conversion is invalid.


We're talking about a malloc() call here. The pointer is required to be
correctly aligned.


Not in that sentence. It's a bald statement that happens to be untrue.
Now, had he said "there is no such thing aa an invalid conversion from
malloc(sizeof(d ouble) to double*" I'd be quick to agree. But he didn't.


I'd agree with that if the line containing the malloc() call wasn't
still present and visible in the post in question.

Richard
Nov 14 '05 #150

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
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...
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
10290
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...
1
7827
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
5681
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...
0
5865
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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.