473,854 Members | 1,516 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 23326
Papadopoulos Giannis <ip******@inf.u th.gr> scribbled the following:
Joona I Palaste wrote:
Papadopoulos Giannis <ip******@inf.u th.gr> scribbled the following:
d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not want stdlib (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.
Note that casting the return value of malloc() *ONLY* shuts up
compiler warnings. It *DOES NOT* fix the code.
Read carefully, because this is important:
*** THE - CODE - IS - STILL - BROKEN!!! ***

I got confused by the older C spec... Sorry...
The older C spec no longer applies. Despite what many C programmers,
both newbies and experienced, might think.
As for the d = (double*)malloc ( 50*sizeof(doubl e) ); d is double*...
Yes, so?
But if I want to make illegal actions, casting is the best... ;)
You shouldn't be making illegal actions at all.
Tnx anyway


Yr wlcm.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"'I' is the most beautiful word in the world."
- John Nordberg
Nov 14 '05 #81
"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.

Richard
Nov 14 '05 #82
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote:
Richard Heathfield wrote:
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.


You can lead a mule to water but you can't make him drink.


You can lead a troll to a newsgroup, but you can't make him think.

Richard
Nov 14 '05 #83
"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.

As it is, I'll just state, flatly, that you're bloody wrong. 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.

Richard
Nov 14 '05 #84
"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.

Richard
Nov 14 '05 #85
Papadopoulos Giannis <ip******@inf.u th.gr> wrote:
d = malloc(50*sizeo f(*d));
--------------------------
o the sortest way
Nope. Lose the parens around *d, then it's the shortest.
o the most portable
o does remember you to include stdlib
s/remember/remind/
o changing type of d does not affect anything
o it looks a bit funny
Not to me it doesn't; it looks perfectly sane.

d = malloc(50*sizeo f(double));
------------------------------
o changing type of d is disastrous
Not for this single line, mind, but now imagine you have three dozen of
such lines in the program. You change a declaration, and all malloc()
calls. Except that you overlook one malloc()...

d = (double*)malloc ( 50*sizeof(doubl e) );
-----------------------------------------
o does not want stdlib
Yes, it does. _Using_ malloc() requires a declaration of malloc(), which
is in <stdlib.h>. (Of course, you could theoretically declare malloc()
by hand. That is legal. It is also not wise.)
(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>.
o it gives a good hint on what d's type is
You should already know. That's what declarations are for.

Am I missing anything else???


Yes. Superfluous pointers confuse the programmer and cost the maintainer
time. Get rid of them.

Richard
Nov 14 '05 #86
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.

Richard
Nov 14 '05 #87
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.. I also do return(EXIT_SUC CESS); :)
d = malloc(50*sizeo f(double));
------------------------------
o changing type of d is disastrous

Not for this single line, mind, but now imagine you have three dozen of
such lines in the program. You change a declaration, and all malloc()
calls. Except that you overlook one malloc()...


Implied...
(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. I tried on win
and linux and managed to carry around a pointer in an int.

Unless, in other implementation a pointer is more than just an int..
Any more info??
Yes. Superfluous pointers confuse the programmer and cost the maintainer
time. Get rid of them.


Got that ;)

Nov 14 '05 #88
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.
--
dik t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~dik/
Nov 14 '05 #89
Papadopoulos Giannis <ip******@inf.u th.gr> scribbled the following:
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.. I also do return(EXIT_SUC CESS); :)
And I suppose you calculate the sum of an array this way?

int ar[(10)];
int i, sum=(0);
for ((i=(0)); ((i)<(10)); (i++)) {
(sum=((sum)+((a r)[(i)])));
}
(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. I tried on win
and linux and managed to carry around a pointer in an int.


Windows and Linux are not the whole world.

--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"As a boy, I often dreamed of being a baseball, but now we must go forward, not
backward, upward, not forward, and always whirling, whirling towards freedom!"
- Kang
Nov 14 '05 #90

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
11027
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
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...
1
7917
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
5743
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...
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
3
3187
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.