why is casting malloc a bad thing?

J

Joona I Palaste

R

Richard Bos

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

Richard Bos

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

Richard Bos

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

Richard Bos

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

Richard Bos

Papadopoulos Giannis said:
d = malloc(50*sizeof(*d));

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

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

Yes, it does. _Using_ malloc() requires a declaration of malloc(), which
(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
 
R

Richard Bos

Papadopoulos Giannis said:
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
 
D

Dik T. Winter

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

Papadopoulos Giannis

Richard said:
Nope. Lose the parens around *d, then it's the shortest.

I like 'em.. I also do return(EXIT_SUCCESS); :)
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...



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 ;)
 
F

Flash Gordon

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.

A matter of opinion.

BTW, you don't need all the brackets.
d = malloc(50 * sizeof *d);
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.

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

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

Joona I Palaste

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)])));
}
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 ([email protected]) ------------- 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
 
P

pete

Richard said:
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.
 
M

Mark A. Odell

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

P.J. Plauger

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
 
R

Richard Bos

Papadopoulos Giannis said:
I like 'em..

Hey, I'm not disputing your choice, only the denomination "shortest". If
you want to write ugly code, be my guest :)
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
 
P

P.J. Plauger

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
 
P

P.J. Plauger

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
 
P

P.J. Plauger

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
 
P

P.J. Plauger

Dik T. Winter said:
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.[/QUOTE]

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
 
P

P.J. Plauger

Especially since original K&R C used the cast.
The cast is the old way. No cast, is the new way.

Sorry, that's not quite right. The cast wasn't required in many/most
early C compilers. Some compilers experimented with stronger type
checking for pointers (a bit of the prior art we drew on when we
decided it was safe and advisable to add stronger type checking
in Standard C). Some of us felt that better documentation of
intended type conversions was advisable. But for whatever reason,
Kernighan at least went through a period when he saw fit to write
the casts.

Great quantities of code existed without casts on malloc calls.
We knew that people would object violently to being forced to
go through all that code and decorate all mslloc calls with casts.
Of course, there were also great quantities of code that didn't
include all necessary headers to get library functions properly
declared (in many cases relying on representation punning between
default int return types and pointers), but it's way easier to
fixup an old source file by adding a few includes.

So it's both simplistic and incorrect to assert:
The cast is the old way. No cast, is the new way.

Four legs good, two legs bad.

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

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

No members online now.

Forum statistics

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

Latest Threads

Top