473,854 Members | 1,449 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
Papadopoulos Giannis <ip******@inf.u th.gr> wrote:
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...


Of course. De gustibus, &c. It's just that _I_ think it's ugly, and as
everybody should know, in matters of taste I am always right ;-)

Richard
Nov 14 '05 #151
qe*@pobox.com (Paul Hsieh) wrote:
Papadopoulos Giannis <ip******@inf.u th.gr> wrote:
d = malloc(50*sizeo f(*d));
--------------------------
o the sortest way
They all generate equivalent object code


Non sequitur.
o the most portable


Its not portable to anal C++ compilers set at their most pedantic
warning level.


Well, duh. It's not portable to Pascal compilers, either. C is not C++.
o does remember you to include stdlib


Or malloc.h on some systems.


If they're broken, perhaps. Which would explain a lot.
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


Or, indeed, equivalent to _any_ kind of integer.
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.


Quite.

Richard
Nov 14 '05 #152
Paul Hsieh wrote:
Papadopoulos Giannis wrote:

d = (double*)malloc ( 50*sizeof(doubl e) ); [...] 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.


There are three situations where the types of d and *d are relevant:

Assign a value: d[10] = 1.5;
Read a value: a[5] = d[10] * 5.3;

Low level memory management including pointer arithmetic:
d = malloc(50 * sizeof(*d));
memcpy(&d[10], &a[5], 5 * sizeof(*d));
a = d + 10;

The latter examples will work for any type of *d, assuming that *a has
the same type. In fact, the type does not matter at all. If you (P.
Giannis) like a good hint in these situations, you will love a good
hint for assign and read, since you will get unexpected results when
d[10] is an integer type. Then, hungarian notation might be the tool
for you, making things worse.
Holger
Nov 14 '05 #153
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.


On the other hand, my opinions on C matters as much as any other
experienced and long-term member of the C community and contributor to
the C language. The fact that I designed C++ doesn't disqualify me
from having valid opinions on C. This is especially true as I present
my opinions in the context of tectnical arguments, rather than as glib
snippets in postings. For example, see my papers on C/C++
compatibility, which you can download from
http://www.research.att.com/~bs/papers.html

-- Bjarne Stroustrup; http://www.research.att.com/~bs
Nov 14 '05 #154
Bjarne Stroustrup <bs@research.at t.com> scribbled the following:
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.
On the other hand, my opinions on C matters as much as any other
experienced and long-term member of the C community and contributor to
the C language. The fact that I designed C++ doesn't disqualify me
from having valid opinions on C. This is especially true as I present
my opinions in the context of tectnical arguments, rather than as glib
snippets in postings. For example, see my papers on C/C++
compatibility, which you can download from
http://www.research.att.com/~bs/papers.html


You are right about that, of course. You are an experienced C programmer
and your opinion about C matters just as much as any other experienced C
programmer's. But the fact that you invented C++ doesn't make your
opinion about C any more special than anyone else's. It just makes your
opinion about _C++_ more special.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Show me a good mouser and I'll show you a cat with bad breath."
- Garfield
Nov 14 '05 #155
Papadopoulos Giannis <ip******@inf.u th.gr> wrote in message news:<bv******* ****@ulysses.no c.ntua.gr>...
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


You have to #include stdlib.h (or somehow have the correct prototype)
regardless.
o changing type of d does not affect anything
o it looks a bit funny
On the contrary, it looks perfectly normal to me.

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

Maybe, maybe not. If you change d to a smaller type, you just
allocated more memory than you needed. Internal fragmentation is
never good, but it's not always disastrous.
d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not want stdlib (but aren't all pointers unsigned ints? - enlight
me plz)
You still have to #include stdlib.h, or somehow have a correct
prototype in scope. Without a prototype in scope, malloc() is assumed
to return int, which may or may not have the same size as a void *.
This means the return value may be truncated or stored incorrectly.
The cast *does not* obviate the need for a correct prototype. All the
cast does is convert the (potentially garbage) return value into a
(potentially invalid) pointer to double.

Pointers need not be the same size or representation as unsigned ints.
Pointers to different types need not be the same size or
representation; e.g., a pointer to int may have a different size and
representation from a pointer to void.
o it gives a good hint on what d's type is
Unless someone changed the type of d.
ï if you change d's type it tells you so

Am I missing anything else???

Nov 14 '05 #156
Richard Bos wrote:
How are casts from malloc() superfluous? Code should work identically
whether the casts are there or not.


Yes. Which is why they're superfluous.


No. Code does not work identically.
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.


How does that invalidate what I said? Whether the programmer thinks so
or not, it does convert an int to pointer. Some int, from somewhere. My
point was that casts on malloc() aren't superfluous, which means more
than what is needed, they just plain are different in this context.

Even when a proper declaration for malloc() is in scope, there are the
cases where there is a pointer mismatch:

int *p;

p = (double *)malloc(sizeof (double));
Still not superfluous in this case. The code works differently without
the cast.
I personally going to stick with no cast. And I think the general case
of C++ compatibility is a non-starter for most applications. I don't
write C code to compiler under C++. When I want C++, I write it.


Brian Rodenborn
Nov 14 '05 #157
In <XT************ *****@nwrddc01. gnilink.net> "P.J. Plauger" <pj*@dinkumware .com> writes:
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.


IIRC, the pre-ANSI C mallloc returned char *. That required an
explicit cast any time its return value was not assigned to a char *.
So, it is very likely that Kernighan was doing it out of habit.

But there is another reason, mentioned in the preface:

We used Bjarne Stroustrup's C++ translator extensively for local
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^
testing of our programs, and Dave Kristol provided us with an ANSI
^^^^^^^^^^^^^^^ ^^^^^^^^
C compiler for final testing.

Since C++ requires the cast, the authors had no chance but to use it.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #158
On 26 Jan 2004 20:50:02 GMT, mw*****@newsguy .com (Michael Wojcik)
wrote:

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?


Stroustrop uses English carefully, and what he stated (in "The C++
Programming Language Third Edition") is subtly different, and compared
to Mark Bruno's statement above, defensible and correct. He actually
states "However, *good* C programs tend to be C++ programs. For
example, every program in Kernighan and Ritchie, The C Programming
Language, 2nd Edition, is a C++ program."(empha sis in the original).

In an appendix he gives an exhaustive treatment of when, and why, C
programs are not C++ programs, and when the two are semantically
different.
Nov 14 '05 #159
On Tue, 27 Jan 2004 00:38:34 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:mi******* *************** **********@4ax. com...
On Mon, 26 Jan 2004 00:29:24 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
>What I find interesting about this debate is the two positions being
>espoused:


Correct. But not these two. The two positions are

1) putting in malloc casts is perfectly ok, its harmless.
2) putting in malloc casts is unnecessary and therefore not ok.


I'm beginning to understand the communication problem here.
I've never espoused either of these posiitons, but that seems
to be what you've read.


I'm finding it hard to read your postings in another way. You're on
record as saying you think that the casts should be there. Charitably
that puts you in group 1.
As I said, I respect you enormously. You mistake intolerance of your
one stupidity for lack of respect


Uh yes, I *do* consider intolerance a lack of respect.


What, you don't have any coworkers or friends who have some small
thing that annoys you? Bullshit, to coin a phrase.
>A closed mind avoids the risk of having to change.


I'd not know, I don't have one.


And yet you can be intolerant. An interesting pair of positions
to reconcile.


When you can explain why, I'll be interested to read it.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 14 '05 #160

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
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
11031
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
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
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
5942
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
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

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.