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

Best regards, Sidney

Nov 14 '05 #191
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's true. In fact, it's more of a "maintenanc e headache" than what
your preferred notation introduces when changing the identifier name
(but only slightly).

Changing an (presumably unique) identifier name is a piece of cake unless
you use a mechanical typewriter for writing source code. But automatically
changing the multiply-used type of an object with a text editor is a bit
more difficult.


It is good to see we are in utter agreement :-)

Best regards, Sidney

Nov 14 '05 #192
Sidney Cadot <si****@jigsaw. nl> wrote:
Richard Bos wrote:
magesh <ma*****@club-internet.fr> wrote:
Well I am not sure to measure upto u guys, my question may be redundnant.
My question is this, if people pretend with their own arguments
that casting malloc return may cause undefined behaviour,


Nonsense - nobody has "pretended" that. Casting malloc() may _hide_
undefined behaviour which is present in the code whether there is a cast
or not. If you call malloc() without a declaration in scope for it, you
always invoke undefined behaviour. The cast doesn't change that fact.

What it does do is stop the compiler from telling you about it.


No, it does not actually. This argument may have been relevant 10 years
ago, but it is no longer. Sure, it's not a required diagnostic in C89
mode, but any halfway decent compiler is able to warn about an
undeclared malloc() nowadays.


And a halfway decent compiler _should_ not warn about problems you have
explicitly cast away.

Richard
Nov 14 '05 #193
Holger Hasselbach wrote:
So I would never write:

intVar = floatVar;

But I would always use an explicit cast (and only in cases where I do
not care too much about rounding).

Occasionally I use explicit casts in that case, too, to silence
over-paranoid compilers ("It's my intention to be unprecise, so shut
up!"). In full awareness that it could introduce serious unwarned bugs
when the intVar is later changed to a longVar without modifying the
cast, when the type is not abstracted by a typedef. But that's another
thing than to not rely on it. To not rely on it has something of to
not trust its correctness of implementation or the correctness of the
rules themself.


Sure, ok. I rely on my compiler to follow the defined semantics, sure,
but I am in disagreement with some semantics, so I avoid relying on
them. Not because of distrust, but because of dislike.

In this respect, implicit void*-to-any* conversion, implicit
float-to-int conversion, and use of trigraphs are in the same "don't do
this" category, in my book.
Why exactly do you think that the float-to-int conversion is
unreasonable?
Because the conversion is inherently impossible to do right without loss
of information, for the mathematical objects that underly floats and
integers.

There's a clear distinction between integers and floats for me, which is
that, within range, the integers behave exactly like their mathematical
cousins. This is not true for floats, they are inherently an
approximation, which I /always/ keep in mind when working with them. For
this reason, I'm not much bothered by int-to-float conversions.
Do you think that an explicit conversion is "more correct" than an
implicit one? I'm quite sure that any existing conforming compiler
will produce exactly the same result in intVar for both cases.
They are semantically equivalent, but not stylistically.
Why exactly do you think that the void*-to-any* conversion is
unreasonable? What exactly could go wrong in the implicit semantics?
There's not so much wrong with void*-to-any* conversion, other than the
fact that it may be done implicitly. This, in my (unpopular) opinion,
allows for what I consider "sloppy typing":

double *x = malloc(50*sizeo f *x);

I firmly believe that the right-hand-side expression should be converted
to the proper type (double *) before doing /anything/ with it (including
assigment). But I am probably alone in thinking that, in this particular
crowd.
Did you have any situations where you experienced the failure of the
implicit conversions (in both int and void), which you successfully
cured with an explicit cast? And that you could blame on the
semantics, not on a broken non-conforming compiler?


No. My style comes from armchair reasoning, not bad experiences.
As I previously wrote far below in the thread, there are three
situations where, for a pointer d, the types of d and *d are relevant:


Only three?

Can you give another one that does not fit into one of these three?


I think that for a pointer d, the types of d and *d are relevant in any
context where it is used, and I believe there are more than three
contexts. But then, you probably meant something more specific.

Best regards,

Sidney

Nov 14 '05 #194
In <bv**********@n ews.tudelft.nl> Sidney Cadot <si****@jigsaw. nl> writes:
Dan Pop wrote:
If you ever have to change identifier names in your code, there is
something very wrong with your coding methodology.


To me, that sounds like a bizarre statement. Please elaborate.


The only *good* reason for renaming an identifier is because the original
name was improperly chosen. Hence my "bizarre" statement above.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #195
In <40******@news2 .power.net.uk> Richard Heathfield <in*****@addres s.co.uk.invalid > writes:
informed opinion); and thank heaven for that, when both sides are using
words like "idiot" and "nonsense". I dread to think what must be going
through the newbies' heads as they read your exchange with Mr Plauger.


Sooner or later, they're bound to discover that Mark McIntyre is clc's
resident idiot and Mr Plauger the author or coauthor of a number of
highly appreciated books about programming.

Of course, this doesn't mean that the former can't right or the latter
can't be wrong, merely that it is highly improbable.

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #196
Sidney Cadot wrote:
magesh wrote:
Well I am not sure to measure upto u guys, my question may be redundnant.
My question is this, if people pretend with their own arguments
that casting malloc return may cause undefined behaviour, I would like
to know

Nobody is pretending that. Both sides agree that not including
<stdlib.h> before using malloc() is very wrong, it is this which causes
UB. Casting or not casting the result of malloc will not lead to
undefined behavior in itself.


I completely agree with the fact that proper header files should be
included, I would be amazed a proper C file that never calls a function
from stdlib, so normal programmers include them, if they give attention
to warnings from the compiler or else this thread is not meant for them.
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's not ok for some (most, actually) for what I'd like to call
stylistic reasons.


Thats what I think, but I agree with fact that unnecessary casts may
fool the compiler and prevent from warning, if not properly used.
I assume that casting the malloc's return is just an indication for my
codevelopers who may see an assignement of p from a malloc a 500 or
more lines after my pointer declaration p.

If you can show me a plausible scenario for this, I'd welcome it. In
practice, malloc() results are almost always assigned to a typed pointer.


declaration of p 1000 lines before.
1001: p= malloc(sizeof(* p)*10);
or
those who don't care of memory
1001: p= malloc(1024);

could you tell me what type is p, while u are going through just this
part of ur code.

1001: p= (int*)malloc(si zeof(int)*10);

Thought it appears newbie ,I think this is more explicit!

Reagrding code maintenance, the other solution p= malloc(sizeof(* p)*10);
may be easy to change the type of p without changing the malloc line in
ur code, after that?? the fact that the type of p has changed may have
more impact on other lines where u use them, than those on one malloc
statement!!!

If we prentend that implicit conversion is safe

No reason to pretend, it is safe (for the result of malloc, anyway).
and the fact of casting may cause UB due to probable alignement problems,

Not for a malloc() result, which is guaranteed to be properly aligned
for conversion to basically any type of pointer.
its a bit difficult to understant why implicit conversion may be safer
than an explicit more than a matter of style.

It is claimed to be safer more from a code-maintenance point of view. In
this respect, some valid arghments do indeed exist.
Does compilers treat them differently?

As far as I know, there are no circumstances where x=y (with x of type
T* and y of type void*) yields a different semantics than x=(T*)y ; if
this is true, it is probable that any real-life compiler will treat
these equivalently.

Yep thats what I expect too.
Best regards,

Sidney

Thanks for ur reply,
regards,
magesh
Nov 14 '05 #197
In <bv**********@n ews.tudelft.nl> Sidney Cadot <si****@jigsaw. nl> writes:
Richard Bos wrote:
magesh <ma*****@club-internet.fr> wrote:

Well I am not sure to measure upto u guys, my question may be redundnant.
My question is this, if people pretend with their own arguments
that casting malloc return may cause undefined behaviour,

Nonsense - nobody has "pretended" that. Casting malloc() may _hide_
undefined behaviour which is present in the code whether there is a cast
or not. If you call malloc() without a declaration in scope for it, you
always invoke undefined behaviour. The cast doesn't change that fact.

What it does do is stop the compiler from telling you about it.


No, it does not actually. This argument may have been relevant 10 years
ago, but it is no longer. Sure, it's not a required diagnostic in C89
mode, but any halfway decent compiler is able to warn about an
undeclared malloc() nowadays.

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

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

Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Nov 14 '05 #198
Dan Pop wrote:
Sidney Cadot <si****@jigsaw. nl> writes:
Dan Pop wrote:
If you ever have to change identifier names in your code,
there is something very wrong with your coding methodology.


To me, that sounds like a bizarre statement. Please elaborate.


The only *good* reason for renaming an identifier is because
the original name was improperly chosen. Hence my "bizarre"
statement above.


Names are originally chosen to make sense to the originator, at
that time. There are many occasions for revision, most of which
are for additional clarity or distinguishment . I keep a utility
around to make mass multiple identifier changes across multiple
files in single passes, and find it very useful at times.

The purpose of the software, the identity of the originator, and
the time are all subject to change, so "improper" is not the
appropriate description.

--
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 #199
On Fri, 30 Jan 2004, Richard Bos wrote:
Tak-Shing Chan <es***@city.ac. uk> wrote:
[snip]
#include <stdio.h>
#include <stdlib.h>

double *x; /* Wrong declaration */
Very unusual. Generally one knows what kind of data one wants when one
declares it; only while using them do you sometimes get confused.


Have you written any program generators? Are all of them
zero-defect implementations ?
int
main(void)
{
x = (int *) malloc(sizeof *x);
if (x) {
*x = 4;
printf("%d\n", *x); /* Undefined behavior */


You know, I'd expect to get a warning;


Which part of the standard mandates such warnings?
and I'd expect malloc()-casters
to cast away that warning by writing

printf("%d\n", (int)*x);

or even

printf("%d\n", *(int *)x);
Your implication that malloc()-casters are doing so just to
shut up the warnings is at best a faulty generalization. When I
do cast malloc, I am trying to get /more/ warnings, not less.
Note that I abhor useless casts, too, so I would never cast this:

int *x = malloc(sizeof *x);

because the type of x is crystal clear in this context. Now,
perhaps, having a mix of casted and uncasted mallocs in the same
translation unit would have the best of both worlds--detecting
missing <stdlib.h> and at the same time detecting type errors:

int *x = malloc(128 * sizeof *x);
if (x) {
foo(128, TYPE_IS_INTEGER , x);
free(x);
}
:
:
:
x = (int *) malloc(2048 * sizeof *x);
if (x) {
bar(2048, TYPE_IS_INTEGER , x);
free(x);
}
With the malloc cast, you are guaranteed a diagnostic.
Without the cast, the diagnostic is not required. Bad style
perhaps, but this possibility should not be dismissed.


Actually, I do dismiss this possibility, because I don't believe it
happens that way.


Yet, it just happened in the above program.
Moreover, it is not a reason to cast malloc() in particular. Would you
also expect to see the cast on

int *y;

y = (int *)x;

If not, why make an exception for malloc()?


No, because the purpose of the diagnostic is to prompt the
programmer to fix the wrong declaration of x. The diagnostic
produced by y = x is a clue to the observant programmer that a
problem has occurred with the type of x or y. On the other hand,
there is not enough information for the implementation to
diagnose the problem in x = malloc(sizeof *x).

Tak-Shing

Nov 14 '05 #200

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