473,839 Members | 1,519 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 23301
On Mon, 26 Jan 2004 00:24:32 -0800
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote:
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'


It's more likely to warn you about implicit conversion of int to
pointer, although the standard does not specify what the diagnostic
should say, only that one must be produced.

However, you should always endeavour to produce code that compiler
without warnings and understand exactly why any warnings that are left
are generated.
o changing type of d does not affect anything
o it looks a bit funny
A matter of opinion.

BTW, you don't need all the brackets.
d = malloc(50 * sizeof *d);
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'


A good compiler *may* warn you depending on whether it is a C99 compiler
and on the level of warnings selected.
(but aren't all pointers unsigned ints? - enlight me plz)


No.


He's right, pointers are definitely NOT unsigned integers. The may be
returned by register in a different register to unsigned ints, they may
be a different size and so on.
o it gives a good hint on what d's type is


So would

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


Horrible. Putting the * by the type instead of the variable leads to
people misreading the declaration. Also, on C90 this style limits where
you can do your allocation.
ï if you change d's type it tells you so

Am I missing anything else?


Yes. You are more likely to get people complain here about your style if
you don't use the form
d = malloc(50 * sizeof *d);
than for the other styles.
--
Flash Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spam, it is real and I read it.
Nov 14 '05 #91
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.

--
pete
Nov 14 '05 #92
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? They have
memory allocation schemes of their own in C++. All my loop indexes are
called 'new' just to prevent accidental C++ compilation C code (okay, not
really).
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.

--
- Mark ->
--
Nov 14 '05 #93
"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.
And precision is everything in our business.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #94
"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 _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.

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 #95
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:40******** ********@news.i ndividual.net.. .
"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.
You know, normally I quite respect you,
you're a damn fine programmer and so forth.

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.


It might be if that's what I asserted, but I didn't. See explanation
in earlier post. It was certainly not my intention to indulge in ad
hominem arguments.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #96
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:40******** ********@news.i ndividual.net.. .
Papadopoulos Giannis <ip******@inf.u th.gr> wrote:
Joona I Palaste wrote:
Papadopoulos Giannis <ip******@inf.u th.gr> scribbled the following:
>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.


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


No, you didn't. void *s didn't officially exist before C89, and pointers
weren't integers in C89, either. In fact, I don't think pointers were
ever a kind of integer, but I don't have any pre-C89 specs, so I can't
be sure.


You're incorrect. In early C, pointers were used to perform unsigned
integer arithmetic reliably. That was before unsigned went into the
language. Later on, but still pre ANSI C, it was widespread practice
to write code that assumed pointers and unsigned ints were freely
interchangeable .

Not that any of this gives modern programmers the least excuse to
ever assume any relationship between the representations of pointers
and integers. They're incommensurate.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #97
"Dik T. Winter" <Di********@cwi .nl> wrote in message
news:Hs******** @cwi.nl...
In article <40************ ****@news.indiv idual.net> rl*@hoekstra-uitgeverij.nl (Richard Bos) writes: ...
> No, you didn't. void *s didn't officially exist before C89, and pointers > weren't integers in C89, either. In fact, I don't think pointers were
> ever a kind of integer, but I don't have any pre-C89 specs, so I can't
> be sure.


Pointers were integers in B. C got rid of that.


Not at first. See previous posting where I discussed the early history
of C. It's fair to say that *Standard C* got rid of the any presumed
relationship between the representations of pointers and integers.

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

Nov 14 '05 #98
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 :-)
(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.


In the typical case, some kinds of pointers may look similar to some
kinds of integers. Note that, contrary to what many people think, modern
desktop computers aren't always "the typical case", though. If it works
on your Wintel box, that doesn't mean it's normal.
For example, it isn't all that long ago (ok, in computer hype terms it's
ancient, but 10 years isn't long ago, honestly) that "the typical
desktop machine" ran MS-DOS, and pointers could be longer than ints
depending on how you compiled your program.
I tried on win and linux and managed to carry around a pointer in an int.
What you may get away with on a desktop toy may not work on a real OS.
Unless, in other implementation a pointer is more than just an int..


It is never _more_ or _less_ than "just an int" - it is something almost
completely different.

What you're saying is similar to the claim that home addresses are just
a number - after all, post codes can be coded into a number without loss
and so can house numbers. It works perfectly, doesn't it? Well, as long
as you don't look over the border it may.
But different countries (read: machine architectures) have different
post code schemes (read: pointer formats), so your encoding may fail if
you move to Italy (read: the Z80). Ok, so some countries may have
different schemes, but surely you can encode addresses in numbers
everywhere, and at least stay valid within that country, in all
countries (read: pointer<->int encodings may not be portable between
machines, but surely the code itself can be used on all computers)?
Well... Some countries don't even use post codes, but some other kind of
addressing (read: some computers use weird pointer formats). And some
may use different post codes within different provinces or states (read:
segmented architectures exist). So no, addresses aren't numbers, and
pointers aren't integers, let alone plain ints.

Richard
Nov 14 '05 #99
E. Robert Tisdale wrote:
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.


And I never said that he did. It is I who respect his reputation, not he who
insists on being respected.

<snip>

--
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 #100

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
9855
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
9697
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,...
1
10647
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
9426
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
7828
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
7017
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
5682
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
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
4064
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.