Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

why is casting malloc a bad thing?

16 views
Skip to first unread message

Brian Blais

unread,
Jan 23, 2004, 8:35:42 AM1/23/04
to
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

Joona I Palaste

unread,
Jan 23, 2004, 9:10:27 AM1/23/04
to
Brian Blais <bbl...@bryant.edu> scribbled the following:
> Hello,

> d=(double *) malloc(50*sizeof(double));

It's not exactly _wrong_ but doesn't help anything either. Why people
discourage it is because of these reasons:
1) There is no need to. malloc(), correctly prototyped, returns a
void *, which is assignable to any object pointer type anyway.
2) If malloc() is not correctly prototyped, casting the return value
won't fix anything. malloc() will still return int, and casting that
int to an object pointer type isn't magically going to change it to a
pointer.
3) If malloc() is not correctly prototyped, the code is broken, because
it causes undefined behaviour. However casting the malloc() will make
the compiler _think_ it's not broken, although it really is.
The correct form is simply:
d = malloc(50*sizeof(double));
or:
d = malloc(50*sizeof *d);

--
/-- Joona Palaste (pal...@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"Hasta la Vista, Abie!"
- Bart Simpson

Mark A. Odell

unread,
Jan 23, 2004, 9:17:13 AM1/23/04
to
Brian Blais <bbl...@bryant.edu> wrote in news:4011232...@bryant.edu:

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

See the C-FAQ as to why.

http://www.eskimo.com/~scs/C-faq/q7.6.html
http://www.eskimo.com/~scs/C-faq/q7.7.html

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

Negative. Void pointers can hold any type of pointer so they naturally
"become" the desired type.

E.g.

void foo(void *pThing)
{
int idx;
char *pChar = pThing;

/* work with pChar */
for (idx = 0; idx < 10; ++idx)
{
pChar[idx] = 'a';
}
}

void bar(void)
{
int arr[100];

foo(arr);
}

No icky casts needed or desired. Void is your friend.

--
- Mark ->
--

Artie Gold

unread,
Jan 23, 2004, 9:20:59 AM1/23/04
to

A pointer to void (void *) can be *implicitly* converted from and to a
pointer to any object type, making the cast unnecessary. It is likely
that the confusion arises from the fact that this was not the case in
pre-ANSI (referred to as K&R) C, where the explicit cast *was* necessary.

The preferred for of the call to malloc() above is:

d = malloc(50 * sizeof *d);

This has several advantages:

It's shorter. ;-)

If one fails to #include <stdlib.h> (in which case the return type of
malloc() reverts to implicit `int') an error will be generated. This is
particularly significant on platforms where the size of `int' and `void
*' differ; in such cases the explicit cast would allow the code to
compile, but behave strangely..

If the type of `d' changes, the form of the malloc() call does not have
to be changed.

In general, casting is evil, except where it's necessary. Since it isn't
necessary in this case, why do it?


This issue has appeared repeatedly on news:comp.lang.c. If you have
further questions, I would recommend searching the archives (through,
for example, http://groups.google.com).

HTH,
--ag
--
Artie Gold -- Austin, Texas

Richard Bos

unread,
Jan 23, 2004, 9:30:33 AM1/23/04
to
Brian Blais <bbl...@bryant.edu> wrote:

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

For the same reason that hanging a "danger - high voltage" sign on a
normal battery is wrong.
Casts are used to circumvent the C type system. If you use them where
the type system does not need to be circumvented, you give off the wrong
signals: that something odd is going on on that line (which it isn't),
and that you're unsure about how the type system works (which you
shouldn't be).

> I had always thought (perhaps mistakenly) that the
> purpose of a void pointer was to cast into a legitimate date type. Is
> this wrong?

This is quite the opposite of right. The purpose of a void * is to help
you _not_ need useless casts all over the place.

Richard

xarax

unread,
Jan 23, 2004, 9:31:45 AM1/23/04
to
"Brian Blais" <bbl...@bryant.edu> wrote in message
news:4011232...@bryant.edu...

You will find folks on both sides of the issue.
The main (some would say *only*) argument against
casting the result is that it will hide the failure
to include <stdlib.h> which declares malloc to return
(void *). The compiler will assume it returns (int),
and casting (int) to (something *) will cause undefined
behavior.

The folks on the other side of the argument say that
their compiler will complain loudly when a function
is referenced without a declaration (implementation-defined behavior), so the
question about including <stdlib.h>
is moot. Once past the question of proper malloc()
declaration, one must contend with the whether the
target pointer is what one intended.

======================
#include <stdlib.h>

static void fubar(void)
{
float * d; /* programmer changed this...! */

/* some dozen lines later in the code */

/* silent erroneous size calculation */
d = malloc(50*sizeof(double));
}
======================

If the programmer decides to change the declaration
of "d", the compiler will *NOT* catch the bad assignment.

If the assignment used a cast (double *), then the
compiler would complain about incompatible pointer
types.

======================
#include <stdlib.h>

static void fubar(void)
{
float * d; /* programmer changed this...! */

/* some dozen lines later in the code */

/* incompatible pointer assignment */
d = (double *) malloc(50*sizeof(double));
}
======================

Another suggestion is *not* to use "sizeof(double)",
but use "sizeof *d", so that the element size changes
automatically when changing the target declaration.

======================
#include <stdlib.h>

static void fubar(void)
{
struct gonk * d; /* programmer changed this...! */

/* some dozen lines later in the code */

/* 50 elements of whatever "d" points to... */
d = malloc(50*sizeof *d);
}
======================

Now the malloc() is compatible with changing the
target type of the pointer variable "d". You can
change it to any kind of pointer type and the
malloc will be compatible. This is the recommended
way to use malloc(), so that:

1. A missing <stdlib.h> is caught.

2. The malloc() assignment is always compatible
with any pointer type.

3. The size calculation changes along with any
change to the target declaration.


If you insist on using sizeof(double) in the size
calculation, then you should cast the result so that
the compiler will complain when the target type is
changed (so that you can change the sizeof() and
recompile). However, you will save yourself some
maintenance headaches by using: "d = malloc(50*sizeof *d);"

2 cents worth. Your mileage may vary.

--
----------------------------
Jeffrey D. Smith
Farsight Systems Corporation
24 BURLINGTON DRIVE
LONGMONT, CO 80501-6906
http://www.farsight-systems.com
z/Debug debugs your Systems/C programs running on IBM z/OS!
Are ISV upgrade fees too high? Check our custom product development!


Roberto DIVIA

unread,
Jan 23, 2004, 8:59:43 AM1/23/04
to

AFAIK it is wrong as <stdlib.h> should already have declared malloc the right
way. By overriding the standard declaration, you risk to re-declare malloc() in
a way it is not ment to. In other words, the <stdlib.h> declaration is the only
correct one, it must work and if it does not it means either that it's broken
or that <stdlib.h> has not been included.

A nice description of the "problem" can be found in:
http://users.powernet.co.uk/eton/c/hackerhotel.html

Ciao,
--
Roberto Divia` Love at first sight is one of the greatest
============= labour-saving devices the world has ever seen.
Mailbox: C02110 CERN-European Organization for Nuclear Research
E-mail: Robert...@cern.ch CH-1211 GENEVE 23, Switzerland

Joona I Palaste

unread,
Jan 23, 2004, 9:42:30 AM1/23/04
to
xarax <xa...@email.com> scribbled the following:

> "Brian Blais" <bbl...@bryant.edu> wrote in message
> news:4011232...@bryant.edu...
>> 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,

> You will find folks on both sides of the issue.
> The main (some would say *only*) argument against
> casting the result is that it will hide the failure
> to include <stdlib.h> which declares malloc to return
> (void *). The compiler will assume it returns (int),
> and casting (int) to (something *) will cause undefined
> behavior.

> The folks on the other side of the argument say that
> their compiler will complain loudly when a function
> is referenced without a declaration (implementation-defined behavior), so the
> question about including <stdlib.h>
> is moot. Once past the question of proper malloc()
> declaration, one must contend with the whether the
> target pointer is what one intended.

I don't understand this argument at all. Without the correct
prototype, using the return value of malloc() causes undefined
behaviour, *CAST OR NO CAST*. The code is broken anyway. *With*
the correct prototype, the cast is completely needless.

> ======================
> #include <stdlib.h>

> static void fubar(void)
> {
> float * d; /* programmer changed this...! */

> /* some dozen lines later in the code */

> /* silent erroneous size calculation */
> d = malloc(50*sizeof(double));
> }
> ======================

> If the programmer decides to change the declaration
> of "d", the compiler will *NOT* catch the bad assignment.

This is why most folks prefer to write:
d = malloc(50*sizeof *d);
and let that solve the problem for them.

> If the assignment used a cast (double *), then the
> compiler would complain about incompatible pointer
> types.

Which would not have ever arisen if they had used the form I
presented above.

> ======================
> #include <stdlib.h>

> static void fubar(void)
> {
> float * d; /* programmer changed this...! */

> /* some dozen lines later in the code */

> /* incompatible pointer assignment */
> d = (double *) malloc(50*sizeof(double));
> }
> ======================

> Another suggestion is *not* to use "sizeof(double)",
> but use "sizeof *d", so that the element size changes
> automatically when changing the target declaration.

Yes, like I just described.

(Snip example)

--
/-- Joona Palaste (pal...@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/

"'It can be easily shown that' means 'I saw a proof of this once (which I didn't
understand) which I can no longer remember'."
- A maths teacher

j

unread,
Jan 23, 2004, 1:06:18 PM1/23/04
to

"Brian Blais" <bbl...@bryant.edu> wrote in message
news:4011232...@bryant.edu...

You do not have to cast a pointer to void as it can be converted to or from
a pointer to any incomplete or object type.

The issue with casting from malloc is not that it is just superfluous
but that you might be suppressing a warning that might otherwise
be useful.


> Brian Blais
>


Mark Bruno

unread,
Jan 23, 2004, 11:17:10 AM1/23/04
to
Casting of void* is required in C++, so i usually do it in C also. It's not
required, but it makes it easier when switching between C and C++, like I
often do.


Mark A. Odell

unread,
Jan 23, 2004, 11:21:16 AM1/23/04
to
"Mark Bruno" <yankees...@yahoo.com> wrote in
news:_-2dnZChZvu...@comcast.com:

> Casting of void* is required in C++, so i usually do it in C also. It's
> not required, but it makes it easier when switching between C and C++,
> like I often do.

So are you saying if I didn't name all my loop variables 'new', 'delete',
'cout', 'cin', etc. I'd have an easier time porting? BTW, why would you
ever use malloc() in C++?

Default User

unread,
Jan 23, 2004, 12:34:53 PM1/23/04
to


You shouldn't be using malloc() in C++ period. Writing code to move back
and forth like that is poor idea. C++ is its own language, and you
should be writing C++ code using the modern libraries. Don't write
cripple C code for C++ applications.

I work in both languages, it's not that hard.

Brian Rodenborn

E. Robert Tisdale

unread,
Jan 23, 2004, 2:36:48 PM1/23/04
to
Brian Blais wrote:

> I saw on a couple of recent posts
> people saying that casting the return value of malloc is bad, like:
>

> double* p = (double*)malloc(50*sizeof(double));
>
> Why is this bad?

It isn't.

> I had always thought (perhaps mistakenly) that
> the purpose of a void pointer was to cast into a legitimate date type.
> Is this wrong?

No.

> Why and what is considered to be correct form?

This is just a style issue.

I always use the explicit cast
to prevent my C++ compiler from complaining about

warning: invalid conversion from `void*' to `double*'

It applies the implicit conversion anyway so it doesn't matter
except that more important warnings some times get lost
if too many warning messages such as this are issued by my compiler.

The important thing here is to adopt a style and stick to it.

Mark A. Odell

unread,
Jan 23, 2004, 3:12:28 PM1/23/04
to
"E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> wrote in
news:401177D0...@jpl.nasa.gov:

Do you really work for NASA yet spew such rubbish?

>> I saw on a couple of recent posts
>> people saying that casting the return value of malloc is bad, like:
>>
>> double* p = (double*)malloc(50*sizeof(double));
>>
>> Why is this bad?
>
> It isn't.

It is not proper C. To the OP, ignore E. Robert Tisdale's response and
read the C-FAQ instead.

>> I had always thought (perhaps mistakenly) that
>> the purpose of a void pointer was to cast into a legitimate date type.
>> Is this wrong?
>
> No.

It is.



>> Why and what is considered to be correct form?
>
> This is just a style issue.

It is not.

> I always use the explicit cast
> to prevent my C++ compiler from complaining about

You *shouldn't* use malloc in C++!



> The important thing here is to adopt a style and stick to it.

True but this is not a style issue.

E. Robert Tisdale

unread,
Jan 23, 2004, 3:32:53 PM1/23/04
to
Mark A. Odell wrote:

> It is not proper C.

Nonsense!
An explicit cast on the value returned from malloc
is *not* explicitly os implicitly prohibited by the ANSI/ISO C standards
and there is *no* C compiler that will complain about it.

Who said anything about using malloc in C++?
I'm just using my C++ compiler to compile C code.

>>The important thing here is to adopt a style and stick to it.
>
> True but this is not a style issue.

If it isn't a style issue, then it is nothing at all.

Mark A. Odell

unread,
Jan 23, 2004, 4:10:44 PM1/23/04
to
"E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> wrote in
news:401184F5...@jpl.nasa.gov:

> Mark A. Odell wrote:
>
>> It is not proper C.
>
> Nonsense!
> An explicit cast on the value returned from malloc
> is *not* explicitly os implicitly prohibited by the ANSI/ISO C standards
> and there is *no* C compiler that will complain about it.

It's not illegal, just not proper. Casts are a punt, you are side-stepping
the C type enforcement. In some cases you must do this (cast) but malloc()
is definitely not one of them.

>
> Who said anything about using malloc in C++?
> I'm just using my C++ compiler to compile C code.

Why when you can tell it to switch ISO C mode? Usually, just giving the
file a .c extension is all that is required. Otherwise, a flag is usually
available to force the file to be treated as C not C++.

>>>The important thing here is to adopt a style and stick to it.
>>
>> True but this is not a style issue.
>
> If it isn't a style issue, then it is nothing at all.

Oh, it's still a punt.

Eric Sosman

unread,
Jan 23, 2004, 4:28:21 PM1/23/04
to
"E. Robert Tisdale" wrote:
>
> Mark A. Odell wrote:
>
> > It is not proper C.
>
> Nonsense!
> An explicit cast on the value returned from malloc
> is *not* explicitly os implicitly prohibited by the ANSI/ISO C standards
> and there is *no* C compiler that will complain about it.

"Not proper" is perhaps too strong. "Not useful" or
"not needed" or "not smart" might have been better.

> Who said anything about using malloc in C++?
> I'm just using my C++ compiler to compile C code.

It's not C code if it's being compiled as C++. Perhaps
you could clarify with a simple test:

#include <stdio.h>
typedef int private;
private main(private class, char **new) {
puts ("Hello, world!");
return 0;
}

If your implementation fails to compile and run this program,
the code is not being processed as C but as something else.

--
Eric....@sun.com

E. Robert Tisdale

unread,
Jan 23, 2004, 5:07:20 PM1/23/04
to
Eric Sosman wrote:

> Perhaps you could clarify with a simple test:
>
> #include <stdio.h>
> typedef int private;
> private main(private class, char **new) {
> puts ("Hello, world!");
> return 0;
> }
>
> If your implementation fails to compile and run this program,
> the code is not being processed as C but as something else.

> cat main.c
#include <stdio.h>

typedef int private;
private main(private class, char* new[]) {
puts("Hello, world!");
return 0;
}

> g++ -x c++ -Dprivate=Private -Dclass=Class -Dnew=New \
-Wall -ansi -pedantic -o main main.c
main.c:4: warning: return type for `main' changed to `int'
> ./main
Hello, world!
> gcc -x c -Dprivate=Private -Dclass=Class -Dnew=New \
-Wall -std=c99 -pedantic -o main main.c
> ./main
Hello, world!

Eric Sosman

unread,
Jan 23, 2004, 6:41:53 PM1/23/04
to

Care to try it again without the -D switches?

Here's the point I'm trying to make: The meaning of a source
file is not contained within the file itself, but only arises
when the file is handed to a compiler or interpreter or whatever.
A C compiler treats the source handed to it as C code; hand that
same source to a C++ compiler and it's C++ code. Hand it to a
COBOL compiler and it's COBOL code.

I once saw an ingeniously constructed source file that
implemented "Hello, world!" in three languages at once: C (pre-
Standard), Fortran (flavor unremembered), and csh. And in natural
languages we have the example of "Mots D'Heures, Gousses, Rames,"
a text that is simultaneously stilted French and phonetic English.
Such exercises, although entertaining and perhaps awe-inspiring,
are not especially practical.

Ordinarily, it's difficult to prepare a source file that's
meaningful in two or more different languages, and even more
difficult to get the different languages to assign the source the
same meaning. But because C and C++ diverged fairly recently,
they have enough in common that it's still possible to write such
ambivalent code fragments. "Possible" doesn't mean "Recommended"
or even "Sane," though: The writing is noticeably cramped, even
if not as perversely contorted as the ForcshtranC tour de farce.
Some may find it amusing to write such hermaphroditic code, but
a recommendation for or against a particular coding practice
should arise from something more than entertainment potential.

Do not pretend that C and C++ are interchangeable, even in
subsetted forms. They are closely related but different languages,
and the attempt to write ambivalent code gives a product that is
neither good C nor good C++. Choose your language and use it to
the hilt; there is no reason to weaken your code with compromise.

--
Eric....@sun.com

E. Robert Tisdale

unread,
Jan 23, 2004, 7:14:37 PM1/23/04
to
Eric Sosman wrote:

> Here's the point I'm trying to make:

[snip]

The point is that nobody claimed that,
"Every C program is a C++ program".

I can't afford to write C code
that cannot also be compiled by a C++ compiler.
We can't afford to support two versions of libraries
one for C programs and another for C++ programs.
We just write code that will compile as either one.


Tom St Denis

unread,
Jan 23, 2004, 7:59:56 PM1/23/04
to

"E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> wrote in message
news:4011B8ED...@jpl.nasa.gov...

Why? Any C compiler suite worth it's bones can compile C code even if it
can also compile C++. Hint: MSVC which is called a C++ compiler can
compile ANSI C [C89 I think] when the filename ends with ".c". Similar for
GCC....

So you really ought to write code that either builds with a "C Compiler" or
a "C++ Compiler" [or just get better tools that can build either].

Tom


Mark Bruno

unread,
Jan 23, 2004, 8:36:19 PM1/23/04
to
Stroutstrup himself has said that all good-style C programs are also C++
programs, so it's just better style. Also, we're not limited to malloc()
here, what if you wrote your own function that returns a generic pointer.
Thirdly, it's always best to be explicit. Lastly, it provides compatibility
with older compilers.


E. Robert Tisdale

unread,
Jan 23, 2004, 8:23:38 PM1/23/04
to
Tom St Denis wrote:

> Any C compiler suite worth it's bones can compile C code
> even if it can also compile C++.

> MSVC, which is called a C++ compiler, can compile ANSI C [C89 I think]


> when the filename ends with ".c".
> Similar for GCC....
>
> So you really ought to write code
> that either builds with a "C Compiler" or a "C++ Compiler"
> [or just get better tools that can build either].

We distribute software packages as source code
which must port to a variety of different platforms.
Our distribution is *much* less attractive
if users must buy and/or install companion C and C++ compilers
before they can actually build the package.

Tom St Denis

unread,
Jan 23, 2004, 9:03:43 PM1/23/04
to

"E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> wrote in message
news:4011C91A...@jpl.nasa.gov...

My point is many compiler suites have BOTH. It just doesn't make sense to
write only a C++ compiler [and not support the few differences in C]. This
is the case for Borland, Microsoft, [iirc] Watcom and GNU compiler suites.

So write portable C code that doesn't use any platform specific headers,
features, or extensions and you're set.

August Derleth

unread,
Jan 23, 2004, 9:43:14 PM1/23/04
to

Tisdale, tell us why we should care about your broken packages,
nonsensical source code, moronic comments, or the broken compiler suites
of your clients. Tell us why comp.lang.c, a group devoted to the
discussion of standard C, should be burdened by your travails or your
nonsense.

Or, better yet, don't. Just leave, and make no comment upon your departure.

--
My address is yvoregnevna gjragl-guerr gjb-gubhfnaq guerr ng lnubb qbg pbz
Note: Rot13 and convert spelled-out numbers to numerical equivalents.


Peter Nilsson

unread,
Jan 23, 2004, 10:07:37 PM1/23/04
to
"Mark A. Odell" <nos...@embeddedfw.com> wrote in message
news:Xns94799AB36B1C3C...@130.133.1.4...

> "E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> wrote in
> news:401177D0...@jpl.nasa.gov:
> >> I saw on a couple of recent posts
> >> people saying that casting the return value of malloc is bad, like:
> >>
> >> double* p = (double*)malloc(50*sizeof(double));
> >>
> >> Why is this bad?
> >
> > It isn't.
>
> It is not proper C.

What is proper C (sic)? Is it anything like baroque C?

> To the OP, ignore E. Robert Tisdale's response
> and read the C-FAQ instead.

Which part? [Have you read 2.14 recently?]

> >> I had always thought (perhaps mistakenly) that
> >> the purpose of a void pointer was to cast into a legitimate date type.
> >> Is this wrong?
> >
> > No.
>
> It is.

The purpose of a void pointer is to implement a generic pointer implicitly
convertable to (almost) any other pointer type.

> >> Why and what is considered to be correct form?
> >
> > This is just a style issue.
>
> It is not.

Then what is it? Feng Shui?

If you think it's a correctness issue, then please provide C&V definitively
proving that the casting of malloc precludes the production of strictly
conforming programs in C.

> > The important thing here is to adopt a style and stick to it.
>
> True but this is not a style issue.

Yes it is. It wasn't once, then it became one with the first standard, and
now it will probably always remain one.

--
Peter


Peter Nilsson

unread,
Jan 23, 2004, 10:37:48 PM1/23/04
to
"Peter Nilsson" <ai...@acay.com.au> wrote in message
news:4011...@news.rivernet.com.au...

> "Mark A. Odell" <nos...@embeddedfw.com> wrote in message
> news:Xns94799AB36B1C3C...@130.133.1.4...
...

> > To the OP, ignore E. Robert Tisdale's response
> > and read the C-FAQ instead.
>
> Which part? [Have you read 2.14 recently?]

Obviously I haven't! I meant 6.16, but Steve removed the casted malloc from
the FAQ since I last glanced at it.

Nonetheless, neither 7.6 nor 7.7 actually state that it is wrong to cast
malloc.

--
Peter


Peter Nilsson

unread,
Jan 23, 2004, 10:58:10 PM1/23/04
to
"Peter Nilsson" <ai...@acay.com.au> wrote in message
news:4011...@news.rivernet.com.au...
> I meant 6.16, but Steve removed the casted malloc from
> the FAQ since I last glanced at it.

Ah, unless I'm having caching problems, he still has the casted form in...

http://www.eskimo.com/~scs/C-faq/q6.16.html

--
Peter


E. Robert Tisdale

unread,
Jan 23, 2004, 11:16:19 PM1/23/04
to
Peter Nilsson wrote:

> Peter Nilsson wrote:
>
>>I meant 6.16, but Steve removed the casted malloc from
>>the FAQ since I last glanced at it.
>
> Ah, unless I'm having caching problems, he still has the casted form in...
>
> http://www.eskimo.com/~scs/C-faq/q6.16.html

That's what I see.

Richard Heathfield

unread,
Jan 24, 2004, 3:09:12 AM1/24/04
to
Mark Bruno wrote:

> Stroutstrup himself has said that all good-style C programs are also C++
> programs,

What he actually said was: "However, /good/ C programs *tend* to be C++
programs". And that's partly wrong (because there are plenty of good C
programs that haven't got a hope of compiling in C++), and partly silly
(because even if they /do/ manage to compile as C++, it won't be /good/
C++).

> so it's just better style.

No, bodging C programs so that they compile in C++ can no more count as
"better style" than bodging C programs so that they compile in C++.

> Also, we're not limited to malloc()
> here, what if you wrote your own function that returns a generic pointer.

I have written such functions. I don't cast when calling them. Why on earth
should I?

> Thirdly, it's always best to be explicit.

Are you sure?

#include <stdio.h>

int main(void)
{
int x = (int)6;
int y = (int)42;
(int)printf((const char *)"%d\n", (int)((int)x+(int)y));
return (int)0;
}

Do you really write your code like that?

> Lastly, it provides
> compatibility with older compilers.

Do you write your function declarators like this?

foo(a, b)
int a;
double b;
{
/* function goes here */

What does C++ think about that?

--
Richard Heathfield : bin...@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

Irrwahn Grausewitz

unread,
Jan 24, 2004, 3:46:00 AM1/24/04
to

FWIW, in the plain text version of the FAQ (that I downloaded
weeks ago from faqs.org, IIRC) I fail to find a single occurrence
of a casted malloc return value - throughout the entire document.

The text version appears to be more up to date than the hypertext
rendition; see Steve Summit's comments in:

http://www.eskimo.com/~scs/C-faq/versions.html

Regards
--
Irrwahn Grausewitz (irrw...@freenet.de)
welcome to clc : http://www.ungerhu.com/jxh/clc.welcome.txt
clc faq-list : http://www.eskimo.com/~scs/C-faq/top.html
acllc-c++ faq : http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

Martin Dickopp

unread,
Jan 24, 2004, 5:32:01 AM1/24/04
to
"E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> writes:

> We can't afford to support two versions of libraries
> one for C programs and another for C++ programs.
> We just write code that will compile as either one.

<OT>
C++ has a standardized way to interface with C code.
</OT>

Martin

Mark McIntyre

unread,
Jan 24, 2004, 9:06:27 AM1/24/04
to
On Fri, 23 Jan 2004 20:36:19 -0500, in comp.lang.c , "Mark Bruno"
<yankees...@yahoo.com> wrote:

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

Well, either you misinterpret him, or he's wrong.

int main(void)
{
int new;
double *x = malloc(12);
}

There's nothing at all stylistically wrong with this C programme but
its not likely to be a C++ one.

>Also, we're not limited to malloc()here, what if you wrote your own function that returns a generic pointer.

Not a problem for C.

>Thirdly, it's always best to be explicit.

For me, its totally obvious what int *p = malloc(12) is doing. Adding
casts merely makes if obfuscated and more error prone.

>Lastly, it provides compatibility
>with older compilers.

This argument would cause you to remove all templates from your C++.
IOW, its bullsh*t

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

Sidney Cadot

unread,
Jan 24, 2004, 9:39:05 AM1/24/04
to
Mark A. Odell wrote:
> Brian Blais <bbl...@bryant.edu> wrote in news:4011232...@bryant.edu:
>
>
>>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));
>
>
> See the C-FAQ as to why.
>
> http://www.eskimo.com/~scs/C-faq/q7.6.html
> http://www.eskimo.com/~scs/C-faq/q7.7.html

Neither of these gives a proper "why".

Section 7.7 comes closest:

"Q. Why does some code carefully cast the values returned by malloc to
the pointer type being allocated?

A. Before ANSI/ISO Standard C introduced the void * generic pointer
type, these casts were typically required to silence warnings (and
perhaps induce conversions) when assigning between incompatible pointer
types. (Under ANSI/ISO Standard C, these casts are no longer necessary.)"

This is a strawman argument: "people using casted mallocs are adhering
to a prehestoric style". Most people that do cast malloc() results
nowadays have other reasons.

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.

For all I care, the FAQ could then go on to explain why this is such a
monumentally silly idea (which I don't think it is, of course).

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.

Best regards,

Sidney

xarax

unread,
Jan 24, 2004, 9:53:01 AM1/24/04
to
"Default User" <first...@boeing.com.invalid> wrote in message
news:40115B3D...@boeing.com.invalid...

> Mark Bruno wrote:
> >
> > Casting of void* is required in C++, so i usually do it in C also. It's not
> > required, but it makes it easier when switching between C and C++, like I
> > often do.
>
>
> You shouldn't be using malloc() in C++ period. Writing code to move back
> and forth like that is poor idea. C++ is its own language, and you
> should be writing C++ code using the modern libraries. Don't write
> cripple C code for C++ applications.

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.

Different languages often demand different
expressions of the same intent, thus different
styles of writing code.


Jack Klein

unread,
Jan 24, 2004, 1:20:22 PM1/24/04
to
On 23 Jan 2004 14:17:13 GMT, "Mark A. Odell" <nos...@embeddedfw.com>
wrote in comp.lang.c:

> Brian Blais <bbl...@bryant.edu> wrote in news:4011232...@bryant.edu:
>
> > 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));
>
> See the C-FAQ as to why.
>
> http://www.eskimo.com/~scs/C-faq/q7.6.html
> http://www.eskimo.com/~scs/C-faq/q7.7.html
>

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

> Negative. Void pointers can hold any type of pointer so they naturally
> "become" the desired type.

[snip]

ITYM "any type of object pointer".

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++
http://www.contrib.andrew.cmu.edu/~ajo/docs/FAQ-acllc.html

Jack Klein

unread,
Jan 24, 2004, 1:30:29 PM1/24/04
to
On Fri, 23 Jan 2004 11:36:48 -0800, "E. Robert Tisdale"
<E.Robert...@jpl.nasa.gov> wrote in comp.lang.c:

> Brian Blais wrote:
>
> > I saw on a couple of recent posts
> > people saying that casting the return value of malloc is bad, like:
> >
> > double* p = (double*)malloc(50*sizeof(double));
> >
> > Why is this bad?
>
> It isn't.
>
> > I had always thought (perhaps mistakenly) that
> > the purpose of a void pointer was to cast into a legitimate date type.
> > Is this wrong?
>
> No.
>
> > Why and what is considered to be correct form?
>
> This is just a style issue.

By and large, the phrase "style issue" is a whine of unprofessional
and/or incompetent programmers.

Professional programmers work to meet requirements. Requirements
apply not only to the operation of the program, but also to the source
code.

Any reasonable set of programming requirements prohibits redundant
casts, as they are a source of coding defects and maintenance
problems.

> I always use the explicit cast
> to prevent my C++ compiler from complaining about

You are free to use anything you like in your code, provided it meets
the given requirements. If you are coding for yourself and the
requirements are your own, well and good. If you program
professionally for an organization that does not have formal
requirements, you are part of a group contributing to the sad state of
software development today.

As to what your C++ compiler complains about, that is of less than no
consequence, and off-topic, here. In this group, C++ literally does
not exist.

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

> It applies the implicit conversion anyway so it doesn't matter
> except that more important warnings some times get lost
> if too many warning messages such as this are issued by my compiler.
>
> The important thing here is to adopt a style and stick to it.

People who use the term "style" actually do not understand the issues.

P.J. Plauger

unread,
Jan 24, 2004, 2:00:24 PM1/24/04
to
"Jack Klein" <jack...@spamcop.net> wrote in message
news:c2e510h9hbjao7qn7...@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.
A compiler is not obliged to detect improper alignment, but if it
does, more power to it. (And this from a person who generally
dislikes warning messages.)

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


Jalapeno

unread,
Jan 24, 2004, 2:52:47 PM1/24/04
to
In article <buu02a$a4a$1...@news.tudelft.nl>,
Sidney Cadot <sid...@jigsaw.nl> wrote:

> 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 should the C FAQ give a ratzass about C++ compilers. Sheesh.

--
"Well, coming from the AeroSpace Manufacturing field, I must add
that titanium is an alloy of aluminum, magnesium and other metals,
so I would assume since titanium is 65% magnesium that it would
react in a very similar manner."
Bill Garber in comp.sys.apple2 Posting-Date: Fri, 07 Feb 2003
03:02:11 -0600 Message-ID: <_E6dndMKLsO...@comcast.com>

Sidney Cadot

unread,
Jan 24, 2004, 2:55:58 PM1/24/04
to
Jalapeno wrote:

> In article <buu02a$a4a$1...@news.tudelft.nl>,
> Sidney Cadot <sid...@jigsaw.nl> wrote:
>
>
>>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 should the C FAQ give a ratzass about C++ compilers. Sheesh.

Is that a question or a statement?

Best regards,

Sidney

Mark McIntyre

unread,
Jan 24, 2004, 5:05:41 PM1/24/04
to
On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
<p...@dinkumware.com> wrote:

>"Jack Klein" <jack...@spamcop.net> wrote in message
>news:c2e510h9hbjao7qn7...@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.

Mark McIntyre

unread,
Jan 24, 2004, 5:06:07 PM1/24/04
to
On Sat, 24 Jan 2004 20:55:58 +0100, in comp.lang.c , Sidney Cadot
<sid...@jigsaw.nl> wrote:

>Jalapeno wrote:
>
>> In article <buu02a$a4a$1...@news.tudelft.nl>,
>> Sidney Cadot <sid...@jigsaw.nl> wrote:
>>
>>
>>>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 should the C FAQ give a ratzass about C++ compilers. Sheesh.
>
>Is that a question or a statement?

Its an expression; :-)

Severian

unread,
Jan 24, 2004, 5:41:48 PM1/24/04
to
On Sat, 24 Jan 2004 22:05:41 +0000, Mark McIntyre
<markmc...@spamcop.net> wrote:

>On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
><p...@dinkumware.com> wrote:
>
>>"Jack Klein" <jack...@spamcop.net> wrote in message
>>news:c2e510h9hbjao7qn7...@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 agree. I worked on a platform years ago that crashed if you accessed
any data type on a non-platform-natural boundary.

At the time -- working on a real world project -- this caused a load
of grief. I felt that the implementation should have provided the
required converions, and some kind of (compile time or run time)
warning that the code code could be inefficient, rather than simply
crashing during execution.

It's not exactly an easy problem for compiler writers, though.

- Sev

E. Robert Tisdale

unread,
Jan 24, 2004, 6:10:38 PM1/24/04
to
Martin Dickopp wrote:

> <OT>
> C++ has a standardized way to interface with C code.
> </OT>

A common misconception.
C++ only has a mechanism (extern "C")
to *help* with linkage.
Neither C or C++ specifies interoperability.
In particular, any two different compilers
(even two different C compilers)
may use a different representation for built-in types,
may use a different protocol to pass arguments and return values,
etcetera.

P.J. Plauger

unread,
Jan 24, 2004, 7:51:25 PM1/24/04
to
"Mark McIntyre" <markmc...@spamcop.net> wrote in message
news:svq510hmo8tlllf4s...@4ax.com...

> On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
> <p...@dinkumware.com> wrote:
>
> >"Jack Klein" <jack...@spamcop.net> wrote in message
> >news:c2e510h9hbjao7qn7...@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.

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

Peter Nilsson

unread,
Jan 24, 2004, 8:04:29 PM1/24/04
to
> On Sat, 24 Jan 2004 22:05:41 +0000, Mark McIntyre
> <markmc...@spamcop.net> wrote:
>
> >On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
> ><p...@dinkumware.com> wrote:
> >
> >>"Jack Klein" <jack...@spamcop.net> wrote in message
> >>news:c2e510h9hbjao7qn7...@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. ...

I'm sure Plauger is more than aware of what the C standard(s) say on the
issue! ;)

The return value for [re|c|m]alloc is correctly aligned for all types,
however, in general, the conversion itself in general is not guaranteed to
be aligned...

char c[sizeof(double)];
void *vp = c;
double *dp = vp; /* potential UB */


"Severian" <seve...@chlamydia-is-not-a-flower.com> wrote in message
news:vns5109r5vm5rl0mp...@4ax.com...


> I agree. I worked on a platform years ago that crashed if you accessed
> any data type on a non-platform-natural boundary.

They are not uncommon.

> At the time -- working on a real world project -- this caused a load
> of grief. I felt that the implementation should have provided the
> required converions, and some kind of (compile time or run time)
> warning that the code code could be inefficient, rather than simply
> crashing during execution.

Implementations are quite limited in being able to repair the damage of bad
source code and practices (see above example). Do you have examples of what
the 'required conversions' should be, and the contexts in which they might
be 'useful'?

> It's not exactly an easy problem for compiler writers, though.

Quite! :-)

--
Peter


Peter Nilsson

unread,
Jan 24, 2004, 8:04:33 PM1/24/04
to
"Jack Klein" <jack...@spamcop.net> wrote in message
news:c2e510h9hbjao7qn7...@4ax.com...
> On Fri, 23 Jan 2004 11:36:48 -0800, "E. Robert Tisdale"
> <E.Robert...@jpl.nasa.gov> wrote in comp.lang.c:
>
> > Brian Blais wrote:
> >
> > > I saw on a couple of recent posts
> > > people saying that casting the return value of malloc is bad, like:
> > >
> > > double* p = (double*)malloc(50*sizeof(double));
> > >
> > > Why is this bad?
> >
> > It isn't.
> >
> > > I had always thought (perhaps mistakenly) that
> > > the purpose of a void pointer was to cast into a legitimate date type.
> > > Is this wrong?
> >
> > No.
> >
> > > Why and what is considered to be correct form?
> >
> > This is just a style issue.
>
> By and large, the phrase "style issue" is a whine of unprofessional
> and/or incompetent programmers. ...

You left out a slur on business acumen.

--
Peter


Allin Cottrell

unread,
Jan 24, 2004, 9:37:29 PM1/24/04
to

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.

--
Allin Cottrell
Department of Economics
Wake Forest University, NC

Severian

unread,
Jan 24, 2004, 10:25:22 PM1/24/04
to

>They are not uncommon.

I know better now; this was ca. 1990.

>> At the time -- working on a real world project -- this caused a load
>> of grief. I felt that the implementation should have provided the
>> required converions, and some kind of (compile time or run time)
>> warning that the code code could be inefficient, rather than simply
>> crashing during execution.
>
>Implementations are quite limited in being able to repair the damage of bad
>source code and practices (see above example). Do you have examples of what
>the 'required conversions' should be, and the contexts in which they might
>be 'useful'?

Well, after we had fixed all the crappy code, we found a compiler
option that would include runtime code to work around alignment
errors. We pulled the original code and ran it; it was something like
40x slower than the fixed code.

>> It's not exactly an easy problem for compiler writers, though.
>
>Quite! :-)

I learned a lot that year!

- Sev

Richard Heathfield

unread,
Jan 25, 2004, 2:13:48 AM1/25/04
to
Allin Cottrell wrote:

> P.J. Plauger wrote:
>> "Mark McIntyre" <markmc...@spamcop.net> wrote in message
>> news:svq510hmo8tlllf4s...@4ax.com...
>>
>>>On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
>>><p...@dinkumware.com> wrote:
>>>
>>>>"Jack Klein" <jack...@spamcop.net> wrote in message
>>>>news:c2e510h9hbjao7qn7...@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.
>>
>>
>> Next step after nonsense -- bullshit. See 6.3.2.3, para. 7.
>
> I seems to me that Mark McIntyre is right.

It seems to /me/ that they are both right, because they are answering
different questions. Mark quite rightly assumes that nobody would be so
stupid as to attempt to perform a conversion such as:

char buf[] = "12345.678";
void *p = buf;
double *d = p; /* Don't Do This */
printf("%f\n", *d); /* And REALLY REALLY Don't Do THIS */

Whereas P J Plauger quite rightly assumes that some people /would/ be so
stupid.

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

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.

P.J. Plauger

unread,
Jan 25, 2004, 2:25:14 AM1/25/04
to
"Richard Heathfield" <inv...@address.co.uk.invalid> wrote in message
news:4013...@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.

pete

unread,
Jan 25, 2004, 9:12:07 AM1/25/04
to
P.J. Plauger wrote:
>
> "Richard Heathfield" <inv...@address.co.uk.invalid> wrote in message
> news:4013...@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

P.J. Plauger

unread,
Jan 25, 2004, 9:37:43 AM1/25/04
to
"pete" <pfi...@mindspring.com> wrote in message
news:4013CE...@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.

Jeremy Yallop

unread,
Jan 25, 2004, 10:32:46 AM1/25/04
to
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.

P.J. Plauger

unread,
Jan 25, 2004, 11:18:39 AM1/25/04
to
"Jeremy Yallop" <jer...@jdyallop.freeserve.co.uk> wrote in message
news:slrnc17ocu...@hehe.cl.cam.ac.uk...

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" <markmc...@spamcop.net> wrote in message
news:svq510hmo8tlllf4s...@4ax.com...

> On Sat, 24 Jan 2004 19:00:24 GMT, in comp.lang.c , "P.J. Plauger"
> <p...@dinkumware.com> wrote:
>
> >"Jack Klein" <jack...@spamcop.net> wrote in message
> >news:c2e510h9hbjao7qn7...@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.

Christian Bau

unread,
Jan 25, 2004, 1:24:09 PM1/25/04
to
In article <buva7e$4ro2$1...@f1n1.spenet.wfu.edu>,
Allin Cottrell <cott...@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).

Sidney Cadot

unread,
Jan 25, 2004, 4:00:03 PM1/25/04
to
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

Richard Heathfield

unread,
Jan 25, 2004, 4:19:39 PM1/25/04
to
Sidney Cadot wrote:

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.

E. Robert Tisdale

unread,
Jan 25, 2004, 4:46:58 PM1/25/04
to
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.

Richard Heathfield

unread,
Jan 25, 2004, 5:31:06 PM1/25/04
to
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.

Sidney Cadot

unread,
Jan 25, 2004, 5:52:09 PM1/25/04
to
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

E. Robert Tisdale

unread,
Jan 25, 2004, 5:43:41 PM1/25/04
to
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.

Mark McIntyre

unread,
Jan 25, 2004, 7:17:39 PM1/25/04
to
On Sun, 25 Jan 2004 16:18:39 GMT, in comp.lang.c , "P.J. Plauger"
<p...@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

unread,
Jan 25, 2004, 7:21:05 PM1/25/04
to
On Sun, 25 Jan 2004 00:51:25 GMT, in comp.lang.c , "P.J. Plauger"
<p...@dinkumware.com> wrote:

>"Mark McIntyre" <markmc...@spamcop.net> wrote in message
>news:svq510hmo8tlllf4s...@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.

Jeremy Yallop

unread,
Jan 25, 2004, 7:26:04 PM1/25/04
to
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.

P.J. Plauger

unread,
Jan 25, 2004, 7:29:24 PM1/25/04
to
"Mark McIntyre" <markmc...@spamcop.net> wrote in message
news:b3n8101t3i1emjm8f...@4ax.com...

> On Sun, 25 Jan 2004 16:18:39 GMT, in comp.lang.c , "P.J. Plauger"
> <p...@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.

E. Robert Tisdale

unread,
Jan 25, 2004, 7:34:55 PM1/25/04
to
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/skeptic/arguments.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.

Allin Cottrell

unread,
Jan 25, 2004, 8:38:13 PM1/25/04
to
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

Richard Heathfield

unread,
Jan 26, 2004, 2:13:59 AM1/26/04
to
E. Robert Tisdale wrote:

You can attempt to substitute slogans for thought, but you can't convince
comp.lang.c that way.

Richard Heathfield

unread,
Jan 26, 2004, 2:23:10 AM1/26/04
to
Mark McIntyre wrote:

> On Sun, 25 Jan 2004 16:18:39 GMT, in comp.lang.c , "P.J. Plauger"
> <p...@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.

Christian Bau

unread,
Jan 26, 2004, 3:02:04 AM1/26/04
to
In article <401460AF...@jpl.nasa.gov>,

"E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> wrote:

> That's an 'Ad Hominen' argument:
>
> http://www.don-lindsay-archive.org/skeptic/arguments.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.

Papadopoulos Giannis

unread,
Jan 26, 2004, 3:09:33 AM1/26/04
to
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???

E. Robert Tisdale

unread,
Jan 26, 2004, 2:58:36 AM1/26/04
to
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.

E. Robert Tisdale

unread,
Jan 26, 2004, 3:24:32 AM1/26/04
to
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));

Papadopoulos Giannis

unread,
Jan 26, 2004, 4:20:58 AM1/26/04
to
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...

Richard Bos

unread,
Jan 26, 2004, 4:31:08 AM1/26/04
to
"Mark Bruno" <yankees...@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

Joona I Palaste

unread,
Jan 26, 2004, 4:40:32 AM1/26/04
to
Papadopoulos Giannis <ipap...@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 (pal...@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/
"The truth is out there, man! Way out there!"
- Professor Ashfield

Christian Bau

unread,
Jan 26, 2004, 4:42:07 AM1/26/04
to
In article <bv2hvo$1t35$2...@ulysses.noc.ntua.gr>,
Papadopoulos Giannis <ipap...@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.

Papadopoulos Giannis

unread,
Jan 26, 2004, 4:48:48 AM1/26/04
to
Joona I Palaste wrote:

> Papadopoulos Giannis <ipap...@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

Christian Bau

unread,
Jan 26, 2004, 4:47:13 AM1/26/04
to
In article <4014dc17....@news.individual.net>,
r...@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...

Joona I Palaste

unread,
Jan 26, 2004, 4:53:02 AM1/26/04
to
Papadopoulos Giannis <ipap...@inf.uth.gr> scribbled the following:
> Joona I Palaste wrote:
>> Papadopoulos Giannis <ipap...@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 (pal...@cc.helsinki.fi) ------------- Finland --------\
\-- http://www.helsinki.fi/~palaste --------------------- rules! --------/

"'I' is the most beautiful word in the world."
- John Nordberg

Richard Bos

unread,
Jan 26, 2004, 4:55:29 AM1/26/04
to
"P.J. Plauger" <p...@dinkumware.com> wrote:

> "Jack Klein" <jack...@spamcop.net> wrote in message
> news:c2e510h9hbjao7qn7...@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

Richard Bos

unread,
Jan 26, 2004, 4:56:52 AM1/26/04
to
"E. Robert Tisdale" <E.Robert...@jpl.nasa.gov> wrote:

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

Richard

Richard Bos

unread,
Jan 26, 2004, 5:00:10 AM1/26/04
to
"P.J. Plauger" <p...@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

Richard Bos

unread,
Jan 26, 2004, 5:01:07 AM1/26/04
to
"E. Robert Tisdale" <E.Robert...@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

Richard Bos

unread,
Jan 26, 2004, 5:41:25 AM1/26/04
to
Papadopoulos Giannis <ipap...@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

Richard Bos

unread,
Jan 26, 2004, 5:44:10 AM1/26/04
to
Papadopoulos Giannis <ipap...@inf.uth.gr> wrote:

> Joona I Palaste wrote:
>
> > Papadopoulos Giannis <ipap...@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

Papadopoulos Giannis

unread,
Jan 26, 2004, 7:07:44 AM1/26/04
to
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 ;)

Dik T. Winter

unread,
Jan 26, 2004, 7:02:01 AM1/26/04
to
In article <4014ef17....@news.individual.net> r...@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/

Joona I Palaste

unread,
Jan 26, 2004, 7:15:26 AM1/26/04
to
Papadopoulos Giannis <ipap...@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 (pal...@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

Flash Gordon

unread,
Jan 26, 2004, 7:08:18 AM1/26/04
to
On Mon, 26 Jan 2004 00:24:32 -0800

"E. Robert Tisdale" <E.Robert...@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.

pete

unread,
Jan 26, 2004, 7:32:48 AM1/26/04
to
Richard Bos wrote:
>
> "E. Robert Tisdale" <E.Robert...@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

Mark A. Odell

unread,
Jan 26, 2004, 8:42:11 AM1/26/04
to
Sidney Cadot <sid...@jigsaw.nl> wrote in
news:buu02a$a4a$1...@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 ->
--

P.J. Plauger

unread,
Jan 26, 2004, 9:23:28 AM1/26/04
to
"Richard Bos" <r...@hoekstra-uitgeverij.nl> wrote in message
news:4014e3ea....@news.individual.net...

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


P.J. Plauger

unread,
Jan 26, 2004, 9:36:54 AM1/26/04
to
"Richard Bos" <r...@hoekstra-uitgeverij.nl> wrote in message
news:4014e486....@news.individual.net...

> "P.J. Plauger" <p...@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

unread,
Jan 26, 2004, 9:42:10 AM1/26/04
to
"Richard Bos" <r...@hoekstra-uitgeverij.nl> wrote in message
news:4014e545....@news.individual.net...

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

unread,
Jan 26, 2004, 9:42:15 AM1/26/04
to
"Richard Bos" <r...@hoekstra-uitgeverij.nl> wrote in message
news:4014ef17....@news.individual.net...

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

unread,
Jan 26, 2004, 9:44:02 AM1/26/04
to
"Dik T. Winter" <Dik.W...@cwi.nl> wrote in message
news:Hs3Ir...@cwi.nl...

> In article <4014ef17....@news.individual.net>
r...@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

Richard Bos

unread,
Jan 26, 2004, 9:36:14 AM1/26/04
to
Papadopoulos Giannis <ipap...@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

Richard Heathfield

unread,
Jan 26, 2004, 10:04:25 AM1/26/04
to
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 : bin...@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

It is loading more messages.
0 new messages