473,889 Members | 1,703 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 23347
On 30 Jan 2004, Daniel Haude wrote:
On Wed, 28 Jan 2004 18:49:52 +0000,
Tak-Shing Chan <es***@city.ac. uk> wrote
in Msg. <Pine.GSO.4.33. 0401281740480.1 8387-100000@swindon>
double *x; /* Wrong declaration */
x = (int *) malloc(sizeof *x);


When you start casting x here, why not cast it everywhere you use it? This
doesn't have to do with malloc().


It has to do with the fact that malloc returns a void *,
which can be assigned to any pointer including the wrong ones.

Tak-Shing

Nov 14 '05 #201
In <bv**********@n ews.tudelft.nl> Sidney Cadot <si****@jigsaw. nl> writes:
Daniel Haude wrote:
On Thu, 29 Jan 2004 01:08:46 +0100,
Sidney Cadot <si****@jigsaw. nl> wrote
in Msg. <bv**********@n ews.tudelft.nl>
That way, I don't have to rely on the semantics of C with regard to
allowing void*-to-any* assignments,

When programming in C you have to rely on the semantics of C with regard
to pretty much anything.


Not at all. For example, I do not have to rely on the semantics of
trigraphs, since I avoid them like the plague.


You may still inadvertently fall upon them, if you're not extremely
careful. E.g.

puts("Huh??!");

This is more of an issue when automatically encoding binary data in
string literals (e.g. using a base64-style algorithm) that are supposed
to be used by C programs. You *must* check that you're not inadvertently
inserting a trigraph sequence in that string literal.

See, their semantics are haunting even the trigraph haters...

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #202
Dan Pop wrote:
Not at all. For example, I do not have to rely on the semantics of
trigraphs, since I avoid them like the plague.

You may still inadvertently fall upon them, if you're not extremely
careful. E.g.

puts("Huh??!");


Like for accidental failure to include <stdlib.h>, my compiler help me
by warning about such mishaps. And yes, this /has/ prevented mayhem once
or twice :-)

Best regards,
Sidney

Nov 14 '05 #203
Dan Pop wrote:
[...]
If you don't use the appropriate command line options to enable such
warnings, that's more of a problem than casting malloc results can ever be.

In short, I think this argument is stale, and is getting staler all the
time.
Try a reality check: how many newbies have you seen enabling such
warnings when they show the way they compiled their code (quite often,
people posting here show their compilation command line)?
All too many, for sure. I wouldn't necessarily recommend malloc casting
to newbies. I wouldn't recommend C to newbies, for that matter.
And keep in mind that this discussion is focused on newbies, experienced
programmers have already defined their preference pro or con casting
void pointers and it is not this thread that is going to make them change
their minds (you will keep casting when this discussion is over, I will
keep avoiding such casts as the plague).


I agree on this for most part, except that this shows a level of
subtlety on this issue that does not rhyme well with the kind of
reactions that code samples with malloc casts invariably evokes
around here.

Best regards,

Sidney

Nov 14 '05 #204
[..snip...]
to the comp.lang.c newsgroup. I find his argument compelling
because it is sound and *not* because of his "reputation ".


[...snip...]

Hmmm...why do we _always_ find you on the opposite bank of the river ? ;)

Cheers,
Amarendra

--
Elementary, my dear Watson. -Holmes.
Nov 14 '05 #205
Ben Pfaff <bl*@cs.stanfor d.edu> wrote in message

[...snip...]
This also avoids a potential problem wherein the roll resists
turning, thereby leading to excessive fragmentation ;-)


To avoid all such issues (mentioned here, as where as elsewhere in
this thread), we use water instead. ;)

Cheers,
Amarendra
Nov 14 '05 #206

In article <bv**********@o ravannahka.hels inki.fi>, Joona I Palaste <pa*****@cc.hel sinki.fi> writes:
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.


Yes, that was rather my point. (The "C2" language is purely an imaginary
invention, created for purposes of withering sarcasm - that may not have
been clear.) And actually, while I respect Stroustrop's opinions on C++,
I wouldn't follow them blindly either.

--
Michael Wojcik mi************@ microfocus.com
Nov 14 '05 #207
Amarendra GODBOLE wrote:

<snip>
--
Elementary, my dear Watson. -Holmes.

Chapter and verse, please! :-)
--
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 #208

In article <ls************ *************** *****@4ax.com>, Bob Doherty <rd*******@eart hlink.net> writes:
On 26 Jan 2004 20:50:02 GMT, mw*****@newsguy .com (Michael Wojcik)
wrote:
I am continually amazed at people who think Stroustrop (I assume this
is whom you meant) magically gets the last word in this argument.
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.


Defensible, certainly, but I disagree with "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).
Yes, I've read that (in the Special Edition, but I believe it's the
same text there), and some of his other writings on the subject.

The second sentence may be correct (I haven't checked every program
in K&R2 to verify this claim). The former, however, is both subjective
("good") and vague ("tend"), so it has no claim to correctness.

Some of the features which make C programs not C++ programs are in fact
attributes of good C programs, as I define them; thus for me good C
programs tend not to be C++ programs.
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.


Indeed. I do not find this a compelling argument for his position
either. I also know the differences between the two languages - which
is good, since I write both C and C++ programs and I like to get them
as right as I can. Yet I have arrived at a different conclusion.

Stroustrop has his opinion on this subject. I don't think it's an
arbitrary, foolish, or malicious one (though I do suspect it's partly
motivated by his relationship to C++ - which is perfectly natural,
and of course he might well hold the same opinion in other circum-
stances). I just don't believe it's a matter of fact, as some people
seem to do.

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

Auden often writes like Disney. Like Disney, he knows the shape of beasts --
(& incidently he, too, might have a company of artists producing his lines) --
unlike Lawrence, he does not know what shapes or motivates these beasts.
-- Dylan Thomas
Nov 14 '05 #209
In article <news:40******* *************** @news.club-internet.fr>
magesh <ma*****@club-internet.fr> writes:
... I would like to know [why]
double* p = malloc(8*sizeof (double));==>OK for some here because
implicit coversion is well enough
but why
double* p = (double*) malloc(8*sizeof (double));==>NO K for some.


It is not so much a "not OK" as "causes more problems than it solves".

Consider, for instance, a (rather weak) analogy. Suppose that for
some reason you have an urgent need to travel 200 miles (or 300 km
in Europe :-) ) in about an hour. You can:

- drive your car at 200 mph (300 kph), or

- take a 500-mph plane, giving you about 30 minutes to get on
and off the plane at the two ends of the travel.

There are tradeoffs here, and neither solution is absolutely perfect
-- but one is statistically quite a bit more risky than the other.
Perhaps driving at 200 mph kills 17% of the people who do it, while
flying at 500 mph kills 0.0034% of people who do it.

In *my* experience -- which dates back to 1981, when I first
started using C -- it is "casting malloc" that is like "driving 200
mph". *Many* more programs that have a cast have been discovered
to be broken, yet produced no compile-time diagnostics at all.

Specifically, I have seen at least dozens, if not hundreds (I never
kept a count), of cases of code that failed at runtime due to casts
hiding a missing "#include <stdlib.h>" or other declaration of
malloc(). In the compilers we used in the 1980s (including VAX
PCC, Plauger's own Whitesmiths C, VAX/VMS C, and a number of C
compilers for IBM PCs), malloc() had type:

char *malloc();

and casts were required for all situations except "assigning the
result to a variable of type `char *'". Without the cast, you got
a diagnostic, contrary to what Dennis Ritchie's earliest C compilers
did. (Apparently, in the Bad Old Days of:

int i 3; /* initialize i to 3 */

and

printf(2, "error\n"); /* write to file descriptor 2 */

no diagnostics occurred for:

int malloc(); char *p; ... p = malloc(N);

I never used these compilers myself -- by 1981, it was apparently
clear to C compiler writers that this was a bad idea.)

Accordingly, in "K&R-1 C" -- i.e., C as described by the original
White Book and implemented by compilers like PCC and VAX/VMS C --
one usually had to cast malloc(). As a result, if one failed to
declare malloc(), it acquired the "implicit int" declaration. C
being C, writing:

int malloc(); /* implicit */
double *p = (double *)malloc(N * sizeof *p);

normally compiled warning-free. On many machines, it even worked --
but on some machines it failed. If you declared malloc correctly,
either by hand or by including some header file (stdlib.h did not
exist yet and the name and even existence of this header varied),
the code would work on those other machines too.

In December 1989, the ANSI X3J11 committee finalized the original
ANSI C standard; and in this C, the type of malloc() had changed
from:

char *malloc();

to:

void *malloc(size_t) ;

Moreover, "void *" (which had been a useless type that even caused
some compilers to core dump!) now existed, and had a special
assignment-conversion property. Because of this property, it was
now possible to remove the casts from old code, and create new code
without casts:

#include <stdlib.h>
...
double *p = malloc(N * sizeof *p);

Such code immediately drew a "diagnostic " -- always a "warning" in
every compiler I used in the 1990s -- if and only if you had
forgotten the "#include" (or a programmer-supplied declaration,
but if you had a Standard C compiler, including the standard header
was the obvious best choice).

In particular, this meant that programs could now be written such
that a VERY COMMON MISTAKE was found at compile time. And -- as
I said earlier -- I subsequently observed what I believe to be
thousands of potential runtime failures, and least dozens of actual
runtime failures, prevented in code in which the (existing) casts
were *removed* and the warning diagnostic fixed by adding the
missing "#include" line.

Had those casts been left in, or had new code been written using
those casts, I believe much more code would have eventually failed
during porting or testing or (most expensively) after distribution.
This leads to what *I* believe is an inescapable conclusion:

IF ONE WRITES IN ANSI C89 (or ISO C90), casting malloc
is not necessary, and adds HUGE amounts of risk.

There are some who argue (see other postings in this thread,
particularly those by Tak-Shing Chan) that, even in strict C89,
there are possible situation in which casting malloc also removes
some risk. But in the the last decade, while I have personally
observed huge numbers of of "failure to include <stdlib.h>" errors,
including dozens of cases in which real, in-use code DID fail
because of this combined with an unnecessary cast, I have never --
NOT ONCE -- seen a situation in which real, in-use code failed in
a way that would have been diagnosed at compile time had a cast
been used. In other words, we might restate the above as:

In C89, casting the result of malloc() has proven over time to
add significant risk of error, and has a theoretical chance of
reducing error. Statistically, code that does cast malloc()
contains many more errors than code that does not.

The only sensible conclusion to the above is that one should not
cast malloc()'s return value in this case -- only some sort of
external constraint (such as "I am not always using C89") could
change this.

Now, in C99, that huge risk -- the failure to declare malloc()
using "#include <stdlib.h>" -- has changed from a frequently-undiagnosed
error to a required-diagnostic error. In other languages that
vaguely resemble C, it has always required a diagnostic. Thus, in
these non-C89 languages, the biggest risk in casting malloc() has
been removed. So we can add:

IF ONE WRITES ONLY IN C99 (or some other non-C language),
casting the result of malloc() adds little if any risk of
error.

Of course, no one yet has a decade of experience in "time-tested"
or "proven" C99 risk-assessment -- the new standard has been in
existence for less than four years, and few compilers implement it
even today. (Whether you believe my own "time-tested, proven" C89
risk-assessment above is up to you, of course.)

In any case, each programmer (or person directing programmers and
thus setting standards for them) must make his own risk/reward
analysis. The risks of casting malloc() in C89 are, I think,
well-established and significant. The rewards are, I think,
nonexistent in practice -- the theoretical situations in which it
helps never occur in real code. The risks in C99 are far smaller;
and if you have additional constraints, or believe you will never
use a C89 compiler that lacks a "warn on implicit int" diagnostic,
your own risk may be smaller than that in "generic C89". In this
case, whether to cast becomes purely a style issue:

While there are many *wrong* styles, there is no single
*right* style.

My own style will continue to be "do not cast", because the casts
are still unnecessary (in C -- I am not writing C++ here and when
I write C++ I almost never use malloc()), and I find that removing
all unnecessary source code produces programs that are smaller,
faster, more comprehensible, and/or more maintainable. But just
as there are English-language styles in which one does not "omit
needless words" (see Strunk&White), there are such code styles too.
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #210

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

33
2303
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
2726
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
2405
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
4389
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
9969
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
9810
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
11203
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
10896
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
10443
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
9612
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
5830
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
4650
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
3257
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.