473,889 Members | 1,674 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
"Richard Heathfield" <in*****@addres s.co.uk.invalid > wrote in message
news:40******@n ews2.power.net. uk...
If my supposition is true, it could certainly explain why they are both so
convinced they're correct. It would also suggest that Mr Plauger owes Mr
McIntyre and Mr Klein an apology.
Or conversely. The bald statements they made were flat wrong.
It is quite plain that neither Jack nor
Mark spoke nonsense, if one only takes a few seconds out to work out the
logic behind their answers.
I understood their logic -- it was incomplete and they were wrong.
Note, also, that the cast (remember that?) doesn't help in this situation.
If you try to convert an undoublypointer y thing into a doublypointeryt hing
by going via void *, the cast will not magically supply this conversion for you.


My point exactly.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #51
P.J. Plauger wrote:

"Richard Heathfield" <in*****@addres s.co.uk.invalid > wrote in message
news:40******@n ews2.power.net. uk...
Or conversely. The bald statements they made were flat wrong. I understood their logic -- it was incomplete and they were wrong.
Note, also, that the cast (remember that?) doesn't help
in this situation.
If you try to convert an undoublypointer y thing into a
doublypointeryt hing by going via void *, the cast will not
magically supply this conversion for you.


My point exactly.


Do you realize that, they were talking about the void pointer
value returned by malloc, as per the subject line of this thread ?

--
pete
Nov 14 '05 #52
"pete" <pf*****@mindsp ring.com> wrote in message
news:40******** ***@mindspring. com...
Do you realize that, they were talking about the void pointer
value returned by malloc, as per the subject line of this thread ?


Looked to me like they were wandering a bit afield of that subject.
Certainly the statements that set me off were pure and unqualified.
But even there they're wrong:

double *pd = malloc(1);

There's no requirement that a malloc call return a pointer
properly aligned for double if the object being allocated is
too small to represent a double. So doctrinaire statements
about the validity of the implicit pointer conversion are
still wrong.

-----

But all this is a red herring. Adding a double cast won't fix the
problem of an improperly aligned void pointer. The brouhaha over
casting void pointers stems from the fact that the C committee
chose to recycle the existing C++ notation for void pointers and
intentionally gave them different semantics. We did a similar
thing with const and with function prototypes. Thus, the C
committee is partly to blame for the subtle dialect differences
between two languages that have an otherwise broad common base.

You can pretend that C++ doesn't exist, or that any matters
C++ are OT here, but that's sticking your head in the sand.
The observable fact is that *many* shops that use C mix it on
a daily basis with C++. Yes, you can ghettoize the two to a
large extent by using extern "C" to communicate between functions
written in the different languages. That's a good discipline
that often does the job. Nevertheless, there are cases where it
makes good project sense to maintain some code in the common
dialect that C and C++ share. That dialect is not bastard and
it is not crippled. Those who try to banish it are, IMO, simply
being silly.

I have no trouble with silliness in most contexts, being silly
about certain issues quite often myself. But I believe it does
a disservice to the lurkers on this newsgroup who are trying
to get educated. They at least deserve a more open consideration
of tradeoffs.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #53
P.J. Plauger wrote:
There's no requirement that a malloc call return a pointer
properly aligned for double if the object being allocated is
too small to represent a double.


There is such a requirement. The standard (both C89 and C99) is a bit
unlcear on this, but defect report #075 is unequivocal:

Question
Item 12 - alignment of allocated memory

Is a piece of memory allocated by malloc required to be aligned
suitably for any type, or only for those types that will fit into
the space? For example, following the assignment:
void *vp = malloc(1);
is it required that (void *)(int *)vp compare equal to vp (assuming
that sizeof(int) > 1), or is it permissible for vp to be a value
not suitably aligned to point to an int?

Response

Subclause 7.10.3 requires allocated memory to be suitably aligned
for any type, so they must compare equal.
<http://std.dkuug.dk/JTC1/SC22/WG14/www/docs/dr_075.html>

Jeremy.
Nov 14 '05 #54
"Jeremy Yallop" <je****@jdyallo p.freeserve.co. uk> wrote in message
news:sl******** ***********@heh e.cl.cam.ac.uk. ..
P.J. Plauger wrote:
There's no requirement that a malloc call return a pointer
properly aligned for double if the object being allocated is
too small to represent a double.
There is such a requirement. The standard (both C89 and C99) is a bit
unlcear on this, but defect report #075 is unequivocal:

Question
Item 12 - alignment of allocated memory

Is a piece of memory allocated by malloc required to be aligned
suitably for any type, or only for those types that will fit into
the space? For example, following the assignment:
void *vp = malloc(1);
is it required that (void *)(int *)vp compare equal to vp (assuming
that sizeof(int) > 1), or is it permissible for vp to be a value
not suitably aligned to point to an int?

Response

Subclause 7.10.3 requires allocated memory to be suitably aligned
for any type, so they must compare equal.
<http://std.dkuug.dk/JTC1/SC22/WG14/www/docs/dr_075.html>


Sigh. Guess I was out of the room when that one went through, or I
would have protested it. The C committee was clear enough when we
discussed our intent for malloc many years ago. Too bad the words
ended up 'a bit unclear' and the intent got reversed in response to
a DR. But so be it.

So the quibble continues. None of which alters the original bald statements
that started this subthread:

-----
"Mark McIntyre" <ma**********@s pamcop.net> wrote in message
news:sv******** *************** *********@4ax.c om...
On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware .com> wrote:
"Jack Klein" <ja*******@spam cop.net> wrote in message
news:c2******* *************** **********@4ax. com...
> 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.


Hm?
If the alignment is incorrect the conversion is invalid.


But its impossible for it to be incorrect. The C Standard says so. If
your h/w platform can't guarantee it, then you can't implement C
there.

-----

I suppose you *can* see the malloc references in all this, but I
confess they're invisible to me.

And the fact remains that the C committee made it permissible to omit
the cast on a malloc call in order to grandfather a gazillion lines
of code with malloc calls written before we strengthened type checking
in C. We did so knowing we were blowing a hole in the type checking
system we cribbed from C++.

If you write malloc calls without casts, it's not because it's
necessarily good programming practice but because your grandfather did.

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

Nov 14 '05 #55
In article <bu***********@ f1n1.spenet.wfu .edu>,
Allin Cottrell <co******@wfu.e du> wrote:
I seems to me that Mark McIntyre is right. The para 7 cited by P.J.
Plauger says:

"A pointer to an object or incomplete type may be converted to a pointer
to a different object or incomplete type. If the resulting pointer is not
correctly aligned for the pointed-to type, the behavior is undefined.
Otherwise, when converted back again, the result shall compare equal to
the original pointer. [...]"

Para 1 of the same section says:

"A pointer to void may be converted to or from a pointer to any incomplete
or object type. A pointer to any incomplete or object type may be converted
to a pointer to void and back again; the result shall compare equal to the
original pointer."

So: para 1 says the void -> double pointer conversion is guaranteed to
produce a correct "round trip", while para 7 states that pointer conversion
*in general* will fail to produce a correct round trip in the case of
misalignment. It follows that misalignment is stipulated to be
impossible in the void -> double case.


That is wrong. double* -> void* -> double* is guaranteed to "work" -
except in the case where the double* is not correctly aligned in which
case you had undefined behavior before you even started!

Misalignment is impossible in the case where (void* -> double* is
defined because the void* had correct alignment), it is quite possible
in the case where (void* -> double* is undefined because the pointer is
not properly aligned).
Nov 14 '05 #56
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.


I'm gonna have myself a t-shirt made with that line :-)

Regards,

Sidney

Nov 14 '05 #57
Sidney Cadot 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.


I'm gonna have myself a t-shirt made with that line :-)


Like most good tee-shirt slogans, it's simply not true. I write malloc calls
without casts because I think the casts do nothing good, and can hide bugs.
Furthermore, neither my father nor my grandfather wrote C programs.

--
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 #58
Richard Heathfield wrote:
Sidney Cadot wrote:
P.J. Plauger wrote:
If you write malloc calls without casts, it's not because it's
necessaril y good programming practice but because your grandfather did.
I'm gonna have myself a t-shirt made with that line :-)


Like most good tee-shirt slogans, it's simply not true.


Wrong!
Tee-shirts *never* lie.
I write malloc calls without casts
because I think the casts do nothing good and can hide bugs.


You only need to accept the fact that you're just wrong.

Nov 14 '05 #59
E. Robert Tisdale wrote:
Richard Heathfield wrote:
Sidney Cadot wrote:
P.J. Plauger wrote:

If you write malloc calls without casts, it's not because it's
necessari ly good programming practice but because your grandfather did.

I'm gonna have myself a t-shirt made with that line :-)
Like most good tee-shirt slogans, it's simply not true.


Wrong!
Tee-shirts *never* lie.


If that's a tee-shirt slogan, it simply proves my point.
I write malloc calls without casts
because I think the casts do nothing good and can hide bugs.


You only need to accept the fact that you're just wrong.


I will be perfectly willing (as my posting history shows) to accept that I'm
wrong if it can be shown that I am in fact wrong. So far, however, you have
not shown me to be wrong.

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

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
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...
0
10794
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
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,...
1
7999
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
7151
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
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
2
4251
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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.