why is casting malloc a bad thing?

R

Richard Heathfield

E. Robert Tisdale said:
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>
 
R

Richard Heathfield

P.J. Plauger said:
Really? Remember the ancient riddle: what walks on four legs in
the morning, two legs in the afternoon, and three legs in the
evening?

A fish!
Few things are as simple as they at first appear.

This is certainly true of the whole malloc thing. I must admit I had no idea
that In The Beginning, malloc casts were not required. (That doesn't change
my opinion that it is unwise - in the main! - for C programmers to provide
the cast.)
 
D

Default User

xarax said:
I interpreted his remark as *not* writing code
that compiles for both C and C++, but that he
doesn't have to change his *style* for either
language.


But you don't cast the result from new in C++, so the "style" is more
consistent not to do that for C either.

At any rate, substance over style says not to cast in C, because it can
hide defects in the code. It can't for C++.



Brian Rodenborn
 
D

Default User

Richard Heathfield wrote:
And I never said that he did. It is I who respect his reputation, not he who
insists on being respected.


That's a foreign concept to Mr. Tisdale, as he has never experienced
respect for his reputation.




Brian Rodenborn
 
D

Default User

P.J. Plauger said:
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.


For many of use, the decision on correctness here comes from experience.
We see a LOT of newbie code, and a common error is to omit the inclusion
of stdlib.h and have that covered up with a cast. Sometimes the cast was
made deliberately to make the compiler shut up.

Now yes, the chances of that happening to an experienced programmer are
slim. Trollsdale will claim it's not a problem because his compiler
warns him about the missing include, and yes most compilers will or can
be set to issue such warnings, but we see the evidence. New programmer
DON'T have their compilers set. And they DO forget the include.

I'm of the opinion like many here that it's cleaner, it's more likely to
be correct, and who cares about C++ anyway? When I'm writing C++, I'll
worry about C++ish things. When I'm writing C, I'll worry about Cish
things.

There may be some people writing common source code libraries, but
that's not most of us, and such people aren't learning to program
anyway. They are also well plugged into the commonalities and
differences between the languages. That doesn't drive a general rule for
all C programmers.




Brian Rodenborn
 
C

Christian Bau

Papadopoulos Giannis said:
I like 'em.. I also do return(EXIT_SUCCESS); :)


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

64 bit Linux is getting quite popular.
 
P

Papadopoulos Giannis

Joona said:
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)])));
}

Don't be so cynic... I do not think it is the same..
 
P

Papadopoulos Giannis

Richard said:
Hey, I'm not disputing your choice, only the denomination "shortest". If
you want to write ugly code, be my guest :)

Ugly style or not, I got used to it and it is really difficult to adopt
a new style...

Anyone who does not like my code, has always the choice of a
beautifier... And I don't think it's all that bad...
 
J

Joona I Palaste

Papadopoulos Giannis said:
Joona said:
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)])));
}
Don't be so cynic... I do not think it is the same..

Then *why* do you use parantheses in return statements? To make return
look like a function, so you can snigger when newbies think it really
*is* a function? =)
 
W

Wayne Throop

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

Let me get this strait.

"Your lack of cast on malloc is traditional,
not a superior programming technique"
and
"You are an idiot"

are considered equally ad hominem. Good to know, good to know.

In the meanwhile, perhaps it isn't too horrible to point out that
adding the cast is duplicated information, (which you might think
is bad, but) which means static checking can diagnose some problems
otherwise difficult to find, and often having to do with writing
past the end of the malloced region, which is Bad, which makes
the apparently bad duplication Good.

To a certain extent, it's a matter of style, but I find that
putting assertions and "redundant" casts in code makes it
significantly more likely to work if it compiles.
Therefore I find this a *useful* style.

But that's just me, and I must say I sympathize with stating
the same type twice (once for size (which is sometimes implicit),
once for typechecking) in the same malloc call.

On the Nth hand, something like

p = malloc(sizeof *p);

is particularly handy, because you can change the type of p
without having to dive into the code everywhere. Better (IMO)
would be something like

p = (typeof *p)malloc(sizeof *p);

but I don't think that works.


Wayne Throop (e-mail address removed) http://sheol.org/throopw
 
M

Michael Wojcik

Stroutstrup himself has said that all good-style C programs are also C++
programs, so it's just better style.

I am continually amazed at people who think Stroustrop (I assume this
is whom you meant) magically gets the last word in this argument. He
clearly has an interest in promoting C++, and that very likely
includes persuading C programmers to switch. What makes you think
he's an impartial observer? For that matter, what makes you think
he's right?

I have just invented a new language, called "C2", which is exactly
like C89 except that all identifiers must be at least 2 characters,
because I don't like single-character identifiers. All "good-style C
programs" are also C2 programs, which proves that 1) C2 is a "better
C", and 2) that avoiding single-character identifiers is "just better
style".

No, you say? Why is this argument valid for Stroustrop and not for
me?
Also, we're not limited to malloc()
here, what if you wrote your own function that returns a generic pointer.

What if I did? The same argument (against casting its return value)
would appear to apply.
Thirdly, it's always best to be explicit.
Why?

Lastly, it provides compatibility with older compilers.

I suspect a very small subset of C programmers need to write code
which is acceptable to both C89 and pre-C89 implementations, or
indeed write for pre-C89 implementations at all. Those who do may
indeed need to cast malloc. Their situation is not the common one,
nor the one we assume on this newsgroup, which is intended for the
discussion of standard C.

--
Michael Wojcik (e-mail address removed)

What is it with this warm, quiet, nauseating bond between them?
-- Rumiko Takahashi, _Maison Ikkoku_, trans. Mari Morimoto, adapt. Gerard
Jones
 
J

Joona I Palaste

Wayne Throop <[email protected]> scribbled the following:

(snip discussion about Trollsdale and PJ Plauger)
In the meanwhile, perhaps it isn't too horrible to point out that
adding the cast is duplicated information, (which you might think
is bad, but) which means static checking can diagnose some problems
otherwise difficult to find, and often having to do with writing
past the end of the malloced region, which is Bad, which makes
the apparently bad duplication Good.

Yes, I agree, but the advantage of *not* casting is that the compiler
warns you about an incorrectly prototyped malloc(), which is a really
serious error, and one which no amount of casting anywhere can fix.
This, in my opinion, *far* outweighs any potential gain you might get
from the static checking you above describe. After all, if the returned
pointer is garbage right from the start, all bounds checking is
completely moot.
On the Nth hand, something like
p = malloc(sizeof *p);
is particularly handy, because you can change the type of p
without having to dive into the code everywhere. Better (IMO)
would be something like
p = (typeof *p)malloc(sizeof *p);
but I don't think that works.

No, that doesn't work, not in C anyway.

--
/-- Joona Palaste ([email protected]) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Remember: There are only three kinds of people - those who can count and those
who can't."
- Vampyra
 
M

Michael Wojcik

Next step after nonsense -- bullshit. See 6.3.2.3, para. 7.

I suspect Mark thought you were claiming that a (non-null) void *
value *returned by malloc* could point to an area that was
incorrectly aligned for double. Of course a void * value obtained
another way (from the address of a pointer to a different type, or
from an uninitialized automatic void* variable, and so forth) may
point to such an area, and assigning such a value to a double* would
be invalid.

I also suspect Mark did not recognize your name, or he might have
double-checked before posting.

Of course, my suspicions may be ill-founded.
 
P

pete

P.J. Plauger said:
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.

You do realise that it's a function of whether the roll
is above or below your elbow, and not a universal constant,
don't you ?
 
J

Joona I Palaste

I am continually amazed at people who think Stroustrop (I assume this
is whom you meant) magically gets the last word in this argument. He
clearly has an interest in promoting C++, and that very likely
includes persuading C programmers to switch. What makes you think
he's an impartial observer? For that matter, what makes you think
he's right?
I have just invented a new language, called "C2", which is exactly
like C89 except that all identifiers must be at least 2 characters,
because I don't like single-character identifiers. All "good-style C
programs" are also C2 programs, which proves that 1) C2 is a "better
C", and 2) that avoiding single-character identifiers is "just better
style".
No, you say? Why is this argument valid for Stroustrop and not for
me?

You are right. Stroustrup's opinion matters on C++, and your opinion
matters on C2, but neither of your (neither's of you?) opinion matters
on C. C++ is Stroustrup's language and C2 is yours, fine, you can keep
them. Neither of you has claim over C.
 
D

Default User

pete said:
You do realise that it's a function of whether the roll
is above or below your elbow, and not a universal constant,
don't you ?


If it's the kind with jokes printed on the roll, then it needs to come
over the top so it will be readable.




Brian Rodenborn
 
J

j

P.J. Plauger said:
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.


I have trouble feeling wrong when I'm trying to state a more
ecumenical position than damn near anybody else in this thread.

I don't think that you are, considering your original replies to both
Jack Klein and Mark McIntyre.

Or to be more succinct: "Nonsense! Bullshit!"
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.

1) Given that casts from malloc _are_ superfluous, why should one
cast?(References to languages other than ISO C are off-topic for this
newsgroup
e.g., ``I do so because I program in C++ at work, so I have adopted this
habit''
-- what you do at work is really irrelevant for this newsgroup, i.e., ERT's
original post)

2) Why should one cast from malloc when it might suppress a warning
which might otherwise be useful? (We all forget to include headers from
time to time)
 
C

CBFalconer

pete said:
You do realise that it's a function of whether the roll
is above or below your elbow, and not a universal constant,
don't you ?

The universal solution, not approved by some style mavens, is to
remove the roll from the dispenser and leave it on the tank. :)
This makes it fairly easy to perform the necessary allocations.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top