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*sizeof(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 22875
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:40******@news2.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 undoublypointery thing into a doublypointerything 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
P.J. Plauger wrote: "Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message news:40******@news2.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 undoublypointery thing into a doublypointerything 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
"pete" <pf*****@mindspring.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
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.
"Jeremy Yallop" <je****@jdyallop.freeserve.co.uk> wrote in message
news:sl*******************@hehe.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**********@spamcop.net> wrote in message
news:sv********************************@4ax.com...
On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger" <pj*@dinkumware.com> wrote:
"Jack Klein" <ja*******@spamcop.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
In article <bu***********@f1n1.spenet.wfu.edu>,
Allin Cottrell <co******@wfu.edu> 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).
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
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.powernet.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
Richard Heathfield wrote: 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.
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.
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 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.
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.powernet.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
Richard Heathfield wrote: Wrong! Tee-shirts *never* lie.
If that's a tee-shirt slogan, it simply proves my point.
Stack overflow - core dumped
Best regards,
Sidney
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.
On Sun, 25 Jan 2004 16:18:39 GMT, in comp.lang.c , "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.
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.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/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 =---
On Sun, 25 Jan 2004 00:51:25 GMT, in comp.lang.c , "P.J. Plauger"
<pj*@dinkumware.com> wrote: "Mark McIntyre" <ma**********@spamcop.net> wrote in message news:sv********************************@4ax.com.. .
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.
Next step after nonsense -- bullshit. See 6.3.2.3, para. 7.
Next step after bullshit - irrelevancy. See 6.3.2.3 para 1.
You might also want to consider that void* is not a pointer to either
an incomplete type, or an object.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.com/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 =---
Mark McIntyre wrote: You might also want to consider that void* is not a pointer to either an incomplete type, or an object.
There are three kinds of type in C: object types, function types and
incomplete types. "void" is an incomplete type.
"The void type comprises an empty set of values; it is an incomplete
type that cannot be completed."
Jeremy.
"Mark McIntyre" <ma**********@spamcop.net> wrote in message
news:b3********************************@4ax.com... On Sun, 25 Jan 2004 16:18:39 GMT, in comp.lang.c , "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.
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.
Thanks very much -- completeness is so hard to achieve in any endeavor
in these complex times.
What I find interesting about this debate is the two positions being
espoused:
1) Omitting casts on malloc calls is acceptable, but not necessarily
virtuous.
2) Putting casts on malloc calls is stupid.
Those of us in the first camp are going to keep using casts, and we're
going to keep respecting those who don't. It would be nice if we were
granted a bit of respect in turn, but what the hell. A closed mind
avoids the risk of having to change.
P.J. Plauger
Dinkumware, Ltd. http://www.dinkumware.com
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: http://www.don-lindsay-archive.org/s...s.html#hominem
Whether P. J. Plauger is complete or incomplete idiot
has no bearing upon whether he is correct or not. :-)
Stupid people use fallacious arguments to persuade other stupid people.
Your personal attack on P. J. Plauger is a clear signal
to all subscribers that you have lost your argument
and descended to name calling instead of withdrawing graciously.
E. Robert Tisdale 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...
It may be cheeky, but it's obviously _not_ an argument ad hominem.
McIntyre does not at all "deduce" the falsity of Plauger's views
on casting the return from malloc from Plauger's (supposed) idiocy.
Allin Cottrell
E. Robert Tisdale 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 attempt to substitute slogans for thought, but you can't convince
comp.lang.c that way.
--
Richard Heathfield : bi****@eton.powernet.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
Mark McIntyre wrote: On Sun, 25 Jan 2004 16:18:39 GMT, in comp.lang.c , "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.
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.
If you're wise, Mark, you'll retract that. Mr Plauger's statement, quoted
above, is IMHO erroneous, but I don't think it's legitimate to call him an
idiot.
He has already stated for the benefit of this newsgroup that (what I
consider to be) his unusual circumstances make it sensible for him to make
his code capable of being compiled under both C and C++; given his
reputation, it makes sense to take him at his word (although that does not
necessarily mean it's sensible to emulate him blindly, in this case; we're
not /all/ writing standard libraries for C and C++ compilers, after all).
I am not forced into the position of choosing which of you is right about
malloc (for I have my own opinion on that, and I like to think that it's an
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.
--
Richard Heathfield : bi****@eton.powernet.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
In article <40**************@jpl.nasa.gov>,
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote: That's an 'Ad Hominen' argument:
http://www.don-lindsay-archive.org/s...s.html#hominem
Whether P. J. Plauger is complete or incomplete idiot has no bearing upon whether he is correct or not. :-)
Stupid people use fallacious arguments to persuade other stupid people. Your personal attack on P. J. Plauger is a clear signal to all subscribers that you have lost your argument and descended to name calling instead of withdrawing graciously.
Tisdale, you shouldn't get involved in a discussion between adults, even
when these adults don't behave as if they are adults.
Considering your history of trolling, forging posts, giving ridiculous
advice to newcomers, any moral judgment coming from you is deeply
unappreciated.
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*sizeof(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*sizeof(*d));
--------------------------
o the sortest way
o the most portable
o does remember you to include stdlib
o changing type of d does not affect anything
o it looks a bit funny
d = malloc(50*sizeof(double));
------------------------------
o changing type of d is disastrous
d = (double*)malloc( 50*sizeof(double) );
-----------------------------------------
o does not want stdlib (but aren't all pointers unsigned ints? - enlight
me plz)
o it gives a good hint on what d's type is
ï if you change d's type it tells you so
Am I missing anything else???
Richard Heathfield wrote: If you're wise, Mark, you'll retract that. Mr. Plauger's statement, quoted above, is IMHO erroneous but I don't think it's legitimate to call him an idiot.
He has already stated for the benefit of this newsgroup that (what I consider to be) his unusual circumstances make it sensible for him to make his code capable of being compiled under both C and C++; given his reputation,
Please note that P. J. Plauger *never* "pulled rank" on you.
As far as I'm concerned Mr. Plauger is just another subscriber
to the comp.lang.c newsgroup. I find his argument compelling
because it is sound and *not* because of his "reputation".
it makes sense to take him at his word (although that does not necessarily mean that it's sensible to emulate him blindly, in this case; we're not /all/ writing standard libraries for C and C++ compilers, after all).
I don't think that
Mr. Plauuger ever argued hardship or special circumstances.
I am not forced into the position of choosing which of you is right about malloc (for I have my own opinion on that, and I like to think that it's an 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.
New subscribers should note that style issues
are the most contentious issues argued in the comp.lang.c newsgroup.
Papadopoulos Giannis wrote: I' ve read nearly completely the whole thread although in the way I lost my path.
I assume the following:
d = malloc(50*sizeof(*d)); -------------------------- o the shortest way o the most portable o does remember you to include stdlib
No. It does *not* remind you to include stdlib.
The best that you can expect is that your compiler
will issue a diagnostic:
warning: implicit declaration of function `malloc'
o changing type of d does not affect anything o it looks a bit funny
d = malloc(50*sizeof(double)); ------------------------------ o changing type of d is disastrous
d = (double*)malloc( 50*sizeof(double) ); ----------------------------------------- o does not warn stdlib
A good C compiler will tell you that
warning: implicit declaration of function `malloc'
(but aren't all pointers unsigned ints? - enlight me plz)
No.
o it gives a good hint on what d's type is
So would
double* d = (double*)malloc(50*sizeof(double));
ï if you change d's type it tells you so
Am I missing anything else?
E. Robert Tisdale wrote: (but aren't all pointers unsigned ints? - enlight me plz)
No.
So??? o it gives a good hint on what d's type is
So would
double* d = (double*)malloc(50*sizeof(double));
I think I wrote it first :) - though, without the leading double* which
is implied indeed...
"Mark Bruno" <ya*************@yahoo.com> wrote:
[ Imprimis, while snipping is good, snipping every single bit of context
is not. ] Stroutstrup himself has said that all good-style C programs are also C++ programs,
Well, he's just wrong, then, isn't he? Or rather, he has what I would
consider silly opinions about what is good style in C; good style in C
does _not_ involve useless casts strewn through your code.
so it's just better style.
Let me get this right: someone who is an authority on C++ says something
about C, _so_ it is correct? Don't you think you trust big names a bit
too easily?
Also, we're not limited to malloc() here,
One more reason not to care what a C++ compiler does with C code.
Thirdly, it's always best to be explicit.
Wrong.
Or do you also write
(void) (int_a = (int) int_b);
and
for (i=(size_t)0;
(size_t)i<(size_t)NUMENTRIES;
i=(size_t)((size_t)i+(size_t)1))
if ((int)mung_array((int *)array, (size_t)i)!=(int)0)
break;
Lastly, it provides compatibility with older compilers.
Which, for the average user, is the only reason, and it is one that
should come up rarely, if ever.
OTOH, too many casts engender confusion in the programmer and insecurity
in the maintainer, so they are an abomination.
Richard
Papadopoulos Giannis <ip******@inf.uth.gr> scribbled the following: I' ve read nearly completely the whole thread, although in the way I lost my path.
I assume the following:
d = malloc(50*sizeof(*d)); -------------------------- o the sortest way
Well, the shortest way would be d = malloc(50*sizeof *d), but you're
otherwise right.
o the most portable o does remember you to include stdlib o changing type of d does not affect anything
Yes.
o it looks a bit funny
That's a matter of taste.
d = malloc(50*sizeof(double)); ------------------------------ o changing type of d is disastrous
Right.
d = (double*)malloc( 50*sizeof(double) ); ----------------------------------------- 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!!! ***
o it gives a good hint on what d's type is ï if you change d's type it tells you so
True, but as the code is broken anyway, this is irrelevant.
Am I missing anything else???
No, that's basically it.
--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The truth is out there, man! Way out there!"
- Professor Ashfield
In article <bv***********@ulysses.noc.ntua.gr>,
Papadopoulos Giannis <ip******@inf.uth.gr> wrote: Am I missing anything else???
The only thing that is missing is that many good programmers try to
avoid any unnecessary cast if at all possible:
A cast tells the compiler "Shut up, I know what I am doing". In reality
it means "Shut up, I thought I knew what I was doing when I wrote this,
even though I might have been wrong at the time or things might have
changed and nowadays the code might be completely wrong".
For example, your program might contain an extern function
int nalloc (double x);
Maybe not very clever to have a function with a name very similar to
malloc, but you might have a completely good reason to use that function
name. Suppose this function does something completely different than
malloc, and suppose you type the malloc call wrong:
double* d = nalloc (100 * sizeof (double)); // Error
double* d = (double *) nalloc (100 * sizeof (double)); // No error
So many people have the habit of _never_ using casts if they can be
avoided.
Joona I Palaste wrote: Papadopoulos Giannis <ip******@inf.uth.gr> scribbled the following:d = (double*)malloc( 50*sizeof(double) ); ----------------------------------------- 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...
As for the
d = (double*)malloc( 50*sizeof(double) );
d is double*...
But if I want to make illegal actions, casting is the best... ;)
Tnx anyway
In article <40****************@news.individual.net>, rl*@hoekstra-uitgeverij.nl (Richard Bos) wrote: OTOH, too many casts engender confusion in the programmer and insecurity in the maintainer, so they are an abomination.
Usually goes like this:
"This cast looks useless to me. No good programmer would use useless
casts. I assume that the original author was a good programmer, so he
wouldn't use useless casts, so the cast is not useless. So what is this
damned cast doing that I cannot figure out? "
And now we have a maintenance programmer wasting time to figure out what
a useless cast is good for, because he made the (incorrect) assumption
that the author knew what he was doing...
Papadopoulos Giannis <ip******@inf.uth.gr> scribbled the following: Joona I Palaste wrote: Papadopoulos Giannis <ip******@inf.uth.gr> scribbled the following:d = (double*)malloc( 50*sizeof(double) ); ----------------------------------------- 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(double) );
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.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"'I' is the most beautiful word in the world."
- John Nordberg
"P.J. Plauger" <pj*@dinkumware.com> wrote: "Jack Klein" <ja*******@spamcop.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. 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
"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
"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
"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
Papadopoulos Giannis <ip******@inf.uth.gr> wrote: d = malloc(50*sizeof(*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*sizeof(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(double) ); ----------------------------------------- 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
Papadopoulos Giannis <ip******@inf.uth.gr> wrote: Joona I Palaste wrote:
Papadopoulos Giannis <ip******@inf.uth.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
Richard Bos wrote: d = malloc(50*sizeof(*d)); -------------------------- o the sortest way
Nope. Lose the parens around *d, then it's the shortest.
I like 'em.. I also do return(EXIT_SUCCESS); :) d = malloc(50*sizeof(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 ;)
In article <40****************@news.individual.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/
Papadopoulos Giannis <ip******@inf.uth.gr> scribbled the following: Richard Bos wrote:d = malloc(50*sizeof(*d)); -------------------------- o the sortest way Nope. Lose the parens around *d, then it's the shortest.
I like 'em.. I also do return(EXIT_SUCCESS); :)
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)+((ar)[(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.helsinki.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
On Mon, 26 Jan 2004 00:24:32 -0800
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote: Papadopoulos Giannis wrote: I' ve read nearly completely the whole thread although in the way I lost my path. I assume the following: d = malloc(50*sizeof(*d)); -------------------------- o the shortest way o the most portable o does remember you to include stdlib No. It does *not* remind you to include stdlib. The best that you can expect is that your compiler will issue a diagnostic: warning: implicit declaration of function `malloc'
It's more likely to warn you about implicit conversion of int to
pointer, although the standard does not specify what the diagnostic
should say, only that one must be produced.
However, you should always endeavour to produce code that compiler
without warnings and understand exactly why any warnings that are left
are generated. o changing type of d does not affect anything o it looks a bit funny
A matter of opinion.
BTW, you don't need all the brackets.
d = malloc(50 * sizeof *d);
d = malloc(50*sizeof(double)); ------------------------------ o changing type of d is disastrous d = (double*)malloc( 50*sizeof(double) ); ----------------------------------------- o does not warn stdlib A good C compiler will tell you that warning: implicit declaration of function `malloc'
A good compiler *may* warn you depending on whether it is a C99 compiler
and on the level of warnings selected. (but aren't all pointers unsigned ints? - enlight me plz) No.
He's right, pointers are definitely NOT unsigned integers. The may be
returned by register in a different register to unsigned ints, they may
be a different size and so on. o it gives a good hint on what d's type is So would double* d = (double*)malloc(50*sizeof(double));
Horrible. Putting the * by the type instead of the variable leads to
people misreading the declaration. Also, on C90 this style limits where
you can do your allocation. ï if you change d's type it tells you so Am I missing anything else?
Yes. You are more likely to get people complain here about your style if
you don't use the form
d = malloc(50 * sizeof *d);
than for the other styles.
--
Flash Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spam, it is real and I read it.
Richard Bos wrote: "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.
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.
Especially since original K&R C used the cast.
The cast is the old way. No cast, is the new way.
--
pete
Sidney Cadot <si****@jigsaw.nl> wrote in
news:bu**********@news.tudelft.nl: If the FAQ is to properly reflect the CLC opinion, it should at least mention the counter-argument that failing to cast malloc prevents a C++ compiler from having a fighting chance at compiling your code.
Why would a C++ compiler need to worry about malloc()'ing code? They have
memory allocation schemes of their own in C++. All my loop indexes are
called 'new' just to prevent accidental C++ compilation C code (okay, not
really).
At least, the presentation of the issue would then be honest. Right now, it is an over-simplification of a complicated issue where there are really two sides, I think.
No, two languages. One that has malloc() and does not require a cast and a
language that cannot prohibit the use of the former's memory allocation
function but that does require a cast.
--
- Mark ->
--
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:40****************@news.individual.net... "P.J. Plauger" <pj*@dinkumware.com> wrote:
"Jack Klein" <ja*******@spamcop.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. 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.
Not in that sentence. It's a bald statement that happens to be untrue.
Now, had he said "there is no such thing aa an invalid conversion from
malloc(sizeof(double) to double*" I'd be quick to agree. But he didn't.
And precision is everything in our business.
P.J. Plauger
Dinkumware, Ltd. http://www.dinkumware.com
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:40****************@news.individual.net... "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.
Sorry, I was being cute at the cost of some precision. And I certainly
didn't intend to be insulting with that statement (or the rationale
that preceded it). My point was that you *can* write malloc calls
without casts only because the C committee gave them special
dispensation. We adopted a stronger typing system than in traditional
C with malice aforethought, but we didn't want to force the rewrite
of gazillions of lines of code that had been written without casts.
That would have been the result of adopting the tidier and more
consistent type-conversion rules of C++. We understood that malloc
calls were safer than average, because of the extra semantic
constraints imposed on the object pointers it returns; but we still
created a funny hole that's troublesome in other contexts, and we still
created a gratuitous difference between C and C++. Perhaps we should
have used some other notation in this context, instead of pirating
C++ notation and perverting it. But we did what we did.
As it is, I'll just state, flatly, that you're bloody wrong.
I have trouble feeling wrong when I'm trying to state a more
ecumenical position than damn near anybody else in this thread.
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.
It's fine with me if you adopt this style, particularly having thought
it through. It's less fine that you and others absolutely refuse to
let in the possibility that well meaning people might arrive at a
different conclusion on such a delicate matter of style.
I had a roommate in college whom I had known through most of high
school. He was a bright guy (got consistently better grades than
me) and we mostly got along. But early in our cohabitation, I
discovered that he put a toilet paper roll on the dispenser
backwards from the way I did. Now I had carefully thought through
the matter and worked out which was the right way. Yet this otherwise
intelligent guy had done the same exercise and came up with the
WRONG conclusion. We eventually worked out our differences without
bloodsheed.
The amusing thing about this story is that, for the past thirty
years, I have been unable to recall what MY original position was
or what OUR compromise became. And that lapse doesn't keep me
awake nights.
P.J. Plauger
Dinkumware, Ltd. http://www.dinkumware.com
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:40****************@news.individual.net... "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.
It might be if that's what I asserted, but I didn't. See explanation
in earlier post. It was certainly not my intention to indulge in ad
hominem arguments.
P.J. Plauger
Dinkumware, Ltd. http://www.dinkumware.com
"Richard Bos" <rl*@hoekstra-uitgeverij.nl> wrote in message
news:40****************@news.individual.net... Papadopoulos Giannis <ip******@inf.uth.gr> wrote:
Joona I Palaste wrote:
Papadopoulos Giannis <ip******@inf.uth.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.
You're incorrect. In early C, pointers were used to perform unsigned
integer arithmetic reliably. That was before unsigned went into the
language. Later on, but still pre ANSI C, it was widespread practice
to write code that assumed pointers and unsigned ints were freely
interchangeable.
Not that any of this gives modern programmers the least excuse to
ever assume any relationship between the representations of pointers
and integers. They're incommensurate.
P.J. Plauger
Dinkumware, Ltd. http://www.dinkumware.com
"Dik T. Winter" <Di********@cwi.nl> wrote in message
news:Hs********@cwi.nl... In article <40****************@news.individual.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.
Not at first. See previous posting where I discussed the early history
of C. It's fair to say that *Standard C* got rid of the any presumed
relationship between the representations of pointers and integers.
P.J. Plauger
Dinkumware, Ltd. http://www.dinkumware.com
Papadopoulos Giannis <ip******@inf.uth.gr> wrote: Richard Bos wrote:d = malloc(50*sizeof(*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 :-) (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.
In the typical case, some kinds of pointers may look similar to some
kinds of integers. Note that, contrary to what many people think, modern
desktop computers aren't always "the typical case", though. If it works
on your Wintel box, that doesn't mean it's normal.
For example, it isn't all that long ago (ok, in computer hype terms it's
ancient, but 10 years isn't long ago, honestly) that "the typical
desktop machine" ran MS-DOS, and pointers could be longer than ints
depending on how you compiled your program.
I tried on win and linux and managed to carry around a pointer in an int.
What you may get away with on a desktop toy may not work on a real OS.
Unless, in other implementation a pointer is more than just an int..
It is never _more_ or _less_ than "just an int" - it is something almost
completely different.
What you're saying is similar to the claim that home addresses are just
a number - after all, post codes can be coded into a number without loss
and so can house numbers. It works perfectly, doesn't it? Well, as long
as you don't look over the border it may.
But different countries (read: machine architectures) have different
post code schemes (read: pointer formats), so your encoding may fail if
you move to Italy (read: the Z80). Ok, so some countries may have
different schemes, but surely you can encode addresses in numbers
everywhere, and at least stay valid within that country, in all
countries (read: pointer<->int encodings may not be portable between
machines, but surely the code itself can be used on all computers)?
Well... Some countries don't even use post codes, but some other kind of
addressing (read: some computers use weird pointer formats). And some
may use different post codes within different provinces or states (read:
segmented architectures exist). So no, addresses aren't numbers, and
pointers aren't integers, let alone plain ints.
Richard
E. Robert Tisdale wrote: Richard Heathfield wrote:
If you're wise, Mark, you'll retract that. Mr. Plauger's statement, quoted above, is IMHO erroneous but I don't think it's legitimate to call him an idiot.
He has already stated for the benefit of this newsgroup that (what I consider to be) his unusual circumstances make it sensible for him to make his code capable of being compiled under both C and C++; given his reputation,
Please note that P. J. Plauger *never* "pulled rank" on you.
And I never said that he did. It is I who respect his reputation, not he who
insists on being respected.
<snip>
--
Richard Heathfield : bi****@eton.powernet.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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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
|
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"...
|
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 :
...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
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...
|
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,...
| |