By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,682 Members | 1,086 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,682 IT Pros & Developers. It's quick & easy.

Casting the return value of malloc() ?

P: n/a
Hi,

I have often wondered if casting the return value of malloc() (or
friends) actually helps anything, recent threads here suggest that it
does not .. so I hope to find out.

For instance :

char *tmp = NULL;

tmp = (char *) malloc(1024);

Is there any pointing in casting the return value of malloc? I see
many people do that, but not test the result such as :

if (tmp == (char *) NULL)
.. some code about malloc() failing ...

Is there any point in casting it?

Cheers,
--Tim
Oct 2 '08 #1
Share this Question
Share on Google+
101 Replies


P: n/a
Tinkertim wrote:
Hi,

I have often wondered if casting the return value of malloc() (or
friends) actually helps anything, recent threads here suggest that it
does not .. so I hope to find out.

For instance :

char *tmp = NULL;

tmp = (char *) malloc(1024);

Is there any pointing in casting the return value of malloc?
None what so ever.

--
Ian Collins.
Oct 2 '08 #2

P: n/a
In article <7c**********************************@p49g2000hsd. googlegroups.com>,
Tinkertim <ti*******@gmail.comwrote:
>Hi,

I have often wondered if casting the return value of malloc() (or
friends) actually helps anything, recent threads here suggest that it
does not .. so I hope to find out.
Good to see we're back on familiar ground.

Oct 2 '08 #3

P: n/a
Tinkertim said:
Hi,

I have often wondered if casting the return value of malloc() (or
friends) actually helps anything,
What help do you think it offers? I can't think of any.
recent threads here suggest that it
does not .. so I hope to find out.

For instance :

char *tmp = NULL;

tmp = (char *) malloc(1024);

Is there any pointing in casting the return value of malloc?
It seems completely pointless to me. Do you have any reason for doing it?
I see
many people do that, but not test the result such as :

if (tmp == (char *) NULL)
.. some code about malloc() failing ...

Is there any point in casting it?
Not that I can think of. Testing the return value, on the other hand, is
crucial.

I suggest you find someone who advocates the cast, and ask them why. Most
likely, they won't know. In the event that you find someone who does know
why they're casting, why not present this group with the reason he or she
gives you, and ask us what we think of it?

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 2 '08 #4

P: n/a
On 2 Oct, 10:22, Tinkertim <tinker...@gmail.comwrote:
Hi,

I have often wondered if casting the return value of malloc() (or
friends) actually helps anything, recent threads here suggest that it
does not .. so I hope to find out.

For instance :

char *tmp = NULL;

tmp = (char *) malloc(1024);

Is there any pointing in casting the return value of malloc? I see
many people do that, but not test the result such as :

if (tmp == (char *) NULL)
* *.. some code about malloc() failing ...

Is there any point in casting it?
This is a FAQ
FAQ 7.7b "What's wrong with casting malloc's return value?"

the FAQ lives at http://c-faq.com

C++ requires a cast on the return of malloc(). But malloc()
is unusual in C++ code (an implementation of C++ might need it).
Some people write code that is required to compile under both C and
C++ (eg. library writers). They also might want to cast the return
value of malloc().
--
Nick Keighley

"Those are my principles. If you don't like them, I have others."
- Groucho Marx
Oct 2 '08 #5

P: n/a
On 2 Oct, 10:59, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
On 2 Oct, 10:22, Tinkertim <tinker...@gmail.comwrote:
Hi,
I have often wondered if casting the return value of malloc() (or
friends) actually helps anything, recent threads here suggest that it
does not .. so I hope to find out.
For instance :
char *tmp = NULL;
tmp = (char *) malloc(1024);
Is there any pointing in casting the return value of malloc? I see
many people do that, but not test the result such as :
if (tmp == (char *) NULL)
.. some code about malloc() failing ...
Is there any point in casting it?

This is a FAQ
FAQ 7.7b "What's wrong with casting malloc's return value?"

the FAQ lives athttp://c-faq.com

C++ requires a cast on the return of malloc(). But malloc()
is unusual in C++ code (an implementation of C++ might need it).
Some people write code that is required to compile under both C and
C++ (eg. library writers). They also might want to cast the return
value of malloc().
As far as I understood it (which might be somewhat wrong) actually
casting the return value is unwanted. Am I wrong that without
including stdlib.h the return value is int (or int * cant remember
which exactly) from malloc and so not casting the return value will
provide a warning/error during compilation if you have missed this
header? Whereas casting the value will hide this problem and result in
strange behaviour

Nick

--------
Mesham Parallel Programming Language
www.mesham.net
Oct 2 '08 #6

P: n/a
polas said:

<snip>
As far as I understood it (which might be somewhat wrong) actually
casting the return value is unwanted.
If you mean "unnecessary", you're right.
Am I wrong that without
including stdlib.h the return value is int (or int * cant remember
which exactly) from malloc
In C90, whenever the compiler encounters any call to any function for which
it has not yet seen a declaration, it is required to assume that the
function returns int, even if We Know Different. (And indeed even if the
compiler knows different, which it is allowed to but not required to.)

Since you're assigning the value returned by malloc to a pointer object,
omitting the header therefore gives a type mismatch between int and
pointer, which the compiler is obliged to diagnose - UNLESS you foolishly
cast the diagnosis away.

If pointers are returned in a different way to ints, or if pointers are
longer than ints, or have completely different representations, this can
cause a very real problem.
and so not casting the return value will
provide a warning/error during compilation if you have missed this
header? Whereas casting the value will hide this problem and result in
strange behaviour
Yes, that's almost right - casting the value will hide the problem and
*may* result in strange behaviour. Or it may not. Until your boss is
watching...

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 2 '08 #7

P: n/a
On 2 Oct, 13:12, Richard Heathfield <r...@see.sig.invalidwrote:
polas said:

<snip>
As far as I understood it (which might be somewhat wrong) actually
casting the return value is unwanted.

If you mean "unnecessary", you're right.
Am I wrong that without
including stdlib.h the return value is int (or int * cant remember
which exactly) from malloc

In C90, whenever the compiler encounters any call to any function for which
it has not yet seen a declaration, it is required to assume that the
function returns int, even if We Know Different. (And indeed even if the
compiler knows different, which it is allowed to but not required to.)

Since you're assigning the value returned by malloc to a pointer object,
omitting the header therefore gives a type mismatch between int and
pointer, which the compiler is obliged to diagnose - UNLESS you foolishly
cast the diagnosis away.

If pointers are returned in a different way to ints, or if pointers are
longer than ints, or have completely different representations, this can
cause a very real problem.
and so not casting the return value will
provide a warning/error during compilation if you have missed this
header? Whereas casting the value will hide this problem and result in
strange behaviour

Yes, that's almost right - casting the value will hide the problem and
*may* result in strange behaviour. Or it may not. Until your boss is
watching...

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Right, thanks for the help clearing that one up for me :)

Nick
-----
Mesham Parallel Programming Language
www.mesham.net
Oct 2 '08 #8

P: n/a
On 2 Oct, 12:42, polas <n...@helpforce.comwrote:
On 2 Oct, 10:59, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
On 2 Oct, 10:22, Tinkertim <tinker...@gmail.comwrote:
I have often wondered if casting the return value of malloc() (or
friends) actually helps anything, recent threads here suggest that it
does not .. so I hope to find out.
For instance :
char *tmp = NULL;
tmp = (char *) malloc(1024);
Is there any pointing in casting the return value of malloc? I see
many people do that, but not test the result such as :
if (tmp == (char *) NULL)
.. some code about malloc() failing ...
Is there any point in casting it?
This is a FAQ
FAQ 7.7b "What's wrong with casting malloc's return value?"
the FAQ lives athttp://c-faq.com
C++ requires a cast on the return of malloc(). But malloc()
is unusual in C++ code (an implementation of C++ might need it).
Some people write code that is required to compile under both C and
C++ (eg. library writers). They also might want to cast the return
value of malloc().
and note the "C++" in my answer. C and C++ are different langauges
and the rules are slightly different. The C++ rules may in some
slightly obscure cases lead to C being written to C++ rules.
As far as I understood it (which might be somewhat wrong) actually
casting the return value is unwanted. Am I wrong that without
including stdlib.h the return value is int (or int * cant remember
which exactly)
int
from malloc and so not casting the return value will
provide a warning/error during compilation if you have missed this
header? Whereas casting the value will hide this problem and result in
strange behaviour
yes

--
Nick Keighley
Oct 2 '08 #9

P: n/a
Tinkertim <tinker...@gmail.comwrote:
I have often wondered if casting the return value
of malloc() (or friends) actually helps anything,
...
You should first define what you mean by 'help', then
ask the more basic question of whether casts help
anything period.

--
Peter
Oct 2 '08 #10

P: n/a
In article <8b**********************************@k30g2000hse. googlegroups.com>,
Nick Keighley <ni******************@hotmail.comwrote some good stuff,
leading up to:
....
>An example of someone who writes code that compiles with both
C and C++ is P.J.Plauger. Is he an imbecile or an idiot?

you are on the verge of a plonk
I'm not sure who is the better archetype of the senile old fool: CBF or
McBush.

Oct 3 '08 #11

P: n/a
On Oct 3, 10:27*pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.
The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran. But again, why would you?

Here's the reasons I can think of:
1) For curiosity's sake
2) You are an idiot

What's your reason?

Oct 4 '08 #12

P: n/a

"Old Wolf" <ol*****@inspire.net.nzwrote in message
On Oct 3, 10:27 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
>Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.
>The question is, why would you want to do this?
>You can write programs that compile in both C
and Fortran. But again, why would you?
>Here's the reasons I can think of:
1) For curiosity's sake
2) You are an idiot

What's your reason?
Programs in the common subset of Fortran and C are fit only for the
international obfuscated C competition. Rules may even allow submission to
the Fortran equivalent at the same time.

Now one good question is why use C at all when C++ is a near as makes no
difference a superset of it? However let's say that we decide that we want
to discourage people from using object-orientation, because of certain
drawbacks we see in the methodogy. A politically effective way of doing this
is to ban C++.

OK, so here's a fragment of our C program

void encrypt(unsigned char *data, size_t len)
{
int i;

for(i=0;i<len;i++)
data ^= 0xCC;
}

A few weeks later, the terrible news come through. Our encryption has been
compromised. We need a beter method, and fast.

So we dust off our Sedgewick and realise that there is somethign called the
RSA cryptosystem. This is very much better, and it is not too difficult to
implment, as long as you have a huge integer library. Well we've got one,
but it's in C++.

No problem. Change the file extension to .cpp, and drop in

void encrypt(unsigned char *data, size_t len)
{
bignum prime1(13);
bignum prime2(17);
bignum unfactorisable = prime1 * prime2;

/* (etc) */
}

Now we're back in business. Nothing else needs to be changed. We've dropped
in an emergency C++ bignum library and the code is now C++ and won't compile
under C, but that is small price for turning out our improved encryption on
time.

--
Free games and programming goodies.
http://www.personal.leeds.ac.uk/~bgy1mm

Oct 4 '08 #13

P: n/a
Old Wolf <ol*****@inspire.net.nzwrites:
On Oct 3, 10:27*pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
>Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.

The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran. But again, why would you?

Here's the reasons I can think of:
1) For curiosity's sake
2) You are an idiot

What's your reason?
As we've mentioned several times in this thread, P.J. Plauger seems to
have sound business reasons for doing this. He's posted about it
here; Google it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 4 '08 #14

P: n/a
Old Wolf wrote:
On Oct 3, 10:27 pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
wrote:
>Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.

The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran. But again, why would you?

Here's the reasons I can think of:
1) For curiosity's sake
2) You are an idiot
3) Testing/Simulation.

The first C code I ever built C as C++ as a device driver. In C,
hardware registers were typedefs to an integer type. In C++ the
register types were classes that simulated the hardware behaviour when
read a written. I still use this technique today for testing drivers.

We also compiled application code as C++ to get stricter type checking,
but C compilers and lint have improved considerably in this area.

--
Ian Collins.
Oct 4 '08 #15

P: n/a
Keith Thompson <ks***@mib.orgwrote:
Old Wolf <ol*****@inspire.net.nzwrites:
On Oct 3, 10:27*pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
True, but in the general case they'll be both bad C and worse C++.
_Correct_, yes, but horrible style.
The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran. But again, why would you?

Here's the reasons I can think of:
1) For curiosity's sake
2) You are an idiot

What's your reason?

As we've mentioned several times in this thread, P.J. Plauger seems to
have sound business reasons for doing this.
He does, but so far, he's the only one who has managed to convince me
that _in his specific case_, the advantages outweigh the downsides. In
every other case I've seen, the claim that "but I might want to compile
my C code as C++" is very simply put aside with the argument that you
just should not do that, as there are mechanisms in C++ to make such
half-hearted practices superfluous.

Richard
Oct 6 '08 #16

P: n/a
rl*@hoekstra-uitgeverij.nl (Richard Bos) writes:
Keith Thompson <ks***@mib.orgwrote:
>Old Wolf <ol*****@inspire.net.nzwrites:
On Oct 3, 10:27*pm, Nick Keighley <nick_keighley_nos...@hotmail.com>
Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.

True, but in the general case they'll be both bad C and worse C++.
_Correct_, yes, but horrible style.
As far as I know, the only thing you need to do that I'd consider poor
C style is casting the result of malloc -- and more generally, not
taking advantage of C's implicit conversions for void*.

I'm sure a lot of programmers trying to write code that's compatible
with both C and C++ will write stylistically bad code -- but then a
lot of programmers manage to do that trying to write plain C.

[...]
>As we've mentioned several times in this thread, P.J. Plauger seems to
have sound business reasons for doing this.

He does, but so far, he's the only one who has managed to convince me
that _in his specific case_, the advantages outweigh the downsides. In
every other case I've seen, the claim that "but I might want to compile
my C code as C++" is very simply put aside with the argument that you
just should not do that, as there are mechanisms in C++ to make such
half-hearted practices superfluous.
Agreed. *Most* programmers don't need to write code that compiles as
both C and C++ (and far too many think they do). But to suggest that
*everyone* who does so is stupid, or has stupid customers, is absurd.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 6 '08 #17

P: n/a
Not that I can think of. Testing the return value, on the other hand, is
crucial.

I suggest you find someone who advocates the cast, and ask them why. Most
likely, they won't know. In the event that you find someone who does know
why they're casting, why not present this group with the reason he or she
gives you, and ask us what we think of it?

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999

The professor at my college where I learned C (he was newly hired at
the time; almost 20 years ago) was the first person to teach C at
the university. Previous programming classes were purely pascal.

He was therefore, by defacto standard, the "guru" and not to be
questioned... (at least not by us undergrads).

He was _adamant_ that the malloc() family *required* casts. To this
day,
the only answer I recall him giving is "...to give the compiler a
warm,
fuzzy feeling". To inquire further left one with the feeling that
your next test grade may suffer if you pressed him. Looking back, I
suspect the intimidation was to avoid embarrasment.

The system, as best I recall, was some type of VAX. It ran a flavor
of Unix, and we compiled our code with "cc" (not gcc). I used that
programming convention for years on many platforms until I read the
CLC FAQ.

To this day, many of us would like to know WHY we were
required to cast for malloc's. I wish I could remember more details.
For all I now, he may have had a reason. Beats me.

Oct 6 '08 #18

P: n/a
RocTheEngy said:
>
>Not that I can think of. Testing the return value, on the other hand, is
crucial.

I suggest you find someone who advocates the cast, and ask them why.
Most likely, they won't know. In the event that you find someone who
does know why they're casting, why not present this group with the
reason he or she gives you, and ask us what we think of it?
The professor at my college where I learned C (he was newly hired at
the time; almost 20 years ago) was the first person to teach C at
the university. Previous programming classes were purely pascal.

He was therefore, by defacto standard, the "guru" and not to be
questioned... (at least not by us undergrads).

He was _adamant_ that the malloc() family *required* casts.
20 years ago, he was *right*.

The language changed... 19 years ago.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 6 '08 #19

P: n/a
On Oct 6, 4:35*pm, Richard Heathfield <r...@see.sig.invalidwrote:
RocTheEngy said:


Not that I can think of. Testing the return value, on the other hand, is
crucial.
I suggest you find someone who advocates the cast, and ask them why.
Most likely, they won't know. In the event that you find someone who
does know why they're casting, why not present this group with the
reason he or she gives you, and ask us what we think of it?
The professor at my college where I learned C (he was newly hired at
the time; almost 20 years ago) was the first person to teach C at
the university. *Previous programming classes were purely pascal.
He was therefore, by defacto standard, the "guru" and not to be
questioned... (at least not by us undergrads).
He was _adamant_ that the malloc() family *required* casts.

20 years ago, he was *right*.

The language changed... 19 years ago.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999- Hide quoted text -

- Show quoted text -
I said _almost_ 20 years ago. :) It was 1991...

But to understand your statement; there was a time when this
convention was correct?
(i.e. required)

Oct 6 '08 #20

P: n/a
RocTheEngy wrote:
>
I said _almost_ 20 years ago. :) It was 1991...

But to understand your statement; there was a time when this
convention was correct?
(i.e. required)
Before C was standardised, void wasn't part of the language and malloc
returned char*

--
Ian Collins.
Oct 6 '08 #21

P: n/a
Flash Gordon <s...@spam.causeway.comwrote:
Nick Keighley wrote, On 03/10/08 09:27:
An example of someone who writes code that compiles
with both C and C++ is P.J.Plauger.
Let's not forget Ritchie and Kernighan.
Is he an imbecile or an idiot?

I *think* he was calling the customers dumbos, not the
authors of the library.
Plauger shares the view of his customers. So any criticism
of his customers must be applied to Plauger himself, if
consistency is to hold.

Here's what he had to say in 2004...

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

--
Peter
Oct 6 '08 #22

P: n/a
Peter Nilsson wrote, On 06/10/08 23:03:
Flash Gordon <s...@spam.causeway.comwrote:
>Nick Keighley wrote, On 03/10/08 09:27:
>>An example of someone who writes code that compiles
with both C and C++ is P.J.Plauger.

Let's not forget Ritchie and Kernighan.
That was because there were no compilers conforming to ANSI C at the
time so they had to use a C++ compiler to get access to certain features.
>>Is he an imbecile or an idiot?
I *think* he was calling the customers dumbos, not the
authors of the library.

Plauger shares the view of his customers. So any criticism
of his customers must be applied to Plauger himself, if
consistency is to hold.
I thought that his view was that it was the right thing for him to do it
because that was his customers' requirement.
Here's what he had to say in 2004...

"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.
He missed a view some espouse...

3) Putting casts on malloc is virtuous
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."
Well, at least some of the people who in general strongly disagree with
putting the casts in have accepted that sometimes there is a good
reason. So not everyone who is against casting has a completely closed
mind :-)
--
Flash Gordon
If spamming me sent it to sm**@spam.causeway.com
If emailing me use my reply-to address
See the comp.lang.c Wiki hosted by me at http://clc-wiki.net/
Oct 8 '08 #23

P: n/a
Flash Gordon wrote:
Peter Nilsson wrote, On 06/10/08 23:03:
>Flash Gordon <s...@spam.causeway.comwrote:
>>Nick Keighley wrote, On 03/10/08 09:27:
An example of someone who writes code that compiles
with both C and C++ is P.J.Plauger.
Let's not forget Ritchie and Kernighan.

That was because there were no compilers conforming to ANSI C at the
time so they had to use a C++ compiler to get access to certain features.
Like void!

I don't think the original K&R even mentions malloc. They do briefly
describe calloc, which is shown as returning char* so a cast is required.

--
Ian Collins.
Oct 8 '08 #24

P: n/a
Flash Gordon <s...@spam.causeway.comwrote:
Peter Nilsson wrote, On 06/10/08 23:03:
Flash Gordon <s...@spam.causeway.comwrote:
Nick Keighley wrote, On 03/10/08 09:27:
An example of someone who writes code that compiles
with both C and C++ is P.J.Plauger.
Let's not forget Ritchie and Kernighan.

That was because there were no compilers conforming to
ANSI C at the time so they had to use a C++ compiler to
get access to certain features.
<http://groups.google.com/group/comp....ea4a63a610cac?
dmode=source>
>Is he an imbecile or an idiot?
I *think* he was calling the customers dumbos, not the
authors of the library.
Plauger shares the view of his customers. So any criticism
of his customers must be applied to Plauger himself, if
consistency is to hold.

I thought that his view was that it was the right thing for
him to do it because that was his customers' requirement.
<http://groups.google.com/group/comp....11d85b17ce318?
dmode=source>

<snip>

--
Peter
Oct 8 '08 #25

P: n/a
On 8 Oct, 02:14, Ian Collins <ian-n...@hotmail.comwrote:
I don't think the original K&R even mentions malloc. *
pp 143 and 167

--
Nick Keighley
Oct 8 '08 #26

P: n/a
Nick Keighley wrote:
On 8 Oct, 02:14, Ian Collins <ian-n...@hotmail.comwrote:
>I don't think the original K&R even mentions malloc.

pp 143 and 167
Not in my 1979 printing. You are thinking of K&R2.

--
Ian Collins.
Oct 8 '08 #27

P: n/a
On 4 Oct, 18:40, Old Wolf <oldw...@inspire.net.nzwrote:
On Oct 3, 10:27*pm,Nick Keighley<nick_keighley_nos...@hotmail.com>
wrote:
Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.

The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran.
that's just dumb. Try thinking instead of just repeating dogma.
Fortran doesn't look anything like C. Well written C compiles
with C++. That is a fact.
But again, why would you?

Here's the reasons I can think of:
* 1) For curiosity's sake
* 2) You are an idiot
whatever.

--
Nick Keighley

Oct 8 '08 #28

P: n/a
Nick Keighley wrote:
On 4 Oct, 18:40, Old Wolf <oldw...@inspire.net.nzwrote:
>On Oct 3, 10:27 pm,Nick Keighley<nick_keighley_nos...@hotmail.com>
wrote:
>>Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.
The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran.

that's just dumb. Try thinking instead of just repeating dogma.
Fortran doesn't look anything like C. Well written C compiles
with C++. That is a fact.
No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.

--
Ian Collins.
Oct 8 '08 #29

P: n/a
On 8 Oct, 09:09, Ian Collins <ian-n...@hotmail.comwrote:
Nick Keighley wrote:
On 8 Oct, 02:14, Ian Collins <ian-n...@hotmail.comwrote:
I don't think the original K&R even mentions malloc. *
pp 143 and 167

Not in my 1979 printing. *You are thinking of K&R2.
ah! missed the word "original"! And I don't have
K&R1 at my elbow

--
nick keighley
Oct 8 '08 #30

P: n/a
Nick Keighley wrote:
On 8 Oct, 09:09, Ian Collins <ian-n...@hotmail.comwrote:
>Nick Keighley wrote:
>>On 8 Oct, 02:14, Ian Collins <ian-n...@hotmail.comwrote:
I don't think the original K&R even mentions malloc.
pp 143 and 167
Not in my 1979 printing. You are thinking of K&R2.

ah! missed the word "original"! And I don't have
K&R1 at my elbow
Nor did I until I read your post!

--
Ian Collins.
Oct 8 '08 #31

P: n/a
Ian Collins said:
Nick Keighley wrote:
<snip>
>Well written C compiles with C++. That is a fact.
No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.
And they are "well-written" constructs, too.

Nick, are you really saying that adding a cast to a call to a function
returning void * is either badly-written C or legal C++?

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 8 '08 #32

P: n/a
Nick Keighley wrote:
On 4 Oct, 18:40, Old Wolf <oldw...@inspire.net.nzwrote:
>On Oct 3, 10:27 pm,Nick Keighley<nick_keighley_nos...@hotmail.com>
wrote:
>>Yes C and C++ are different. But you can write a programs
using a LARGE subset of C that will compile with C and C++.
I know it is unfashionable to say this in clc.
But it is none the less true.
The question is, why would you want to do this?

You can write programs that compile in both C
and Fortran.

that's just dumb. Try thinking instead of just repeating dogma.
Fortran doesn't look anything like C. ...
Fortran code can also BE C code - with care, it can even behave in
equivalent ways when compiled with both types of compilers. Of course,
this relies upon complicated tricks that depend upon the different ways
in which the two languages handle comments. No one would recommend doing
so, which I believe was his whole point: it's possible, but why do it?

That approach wouldn't work with C and C++; they're too similar - with
the release of C99 they now have identical syntax for comments. However,
they are also sufficiently similar that you don't need to use that
approach, so the reference to Fortran was a bad argument.
... Well written C compiles
with C++. That is a fact.
It is a falsehood that bears a resemblance to the truth. C can be
written to compile with C++, and most of the restrictions needed to make
it compile with C++ are things that make the C code better (such as
mandatory use of prototypes). C code that compiles under C++ will
usually (but not always) behave the same way as when compiled under C.
With a little bit of additional care, it is possible to modify almost
any strictly conforming C90 program (and most C programs that don't
strictly conform to C90) so that it will compile with the same behavior
under either C or C++. An obvious exception is programs which are
designed to detect which language they were compiled with.

However, well written C code does NOT cast the value returned by
malloc(); and such code is a constraint violation for C++, unless the
destination is also a void*. Well written C code can and sometimes does
make use of identifiers that are reserved in C++. Also, well written C99
code can make use of constructs that are not supported by C++. Many C99
features will be supported in future versions of C++, but that hasn't
happened yet, and many features will never be supported.
Oct 8 '08 #33

P: n/a
In article <0d**********************************@s20g2000prd. googlegroups.com>,
Nick Keighley <ni******************@hotmail.comwrote:
>Well written C compiles with C++. That is a fact.
In that case, to write C well you have to refer to a C++ reference,
because C++ reserves identifiers that a C programmer would otherwise
have no reason to avoid.

-- Richard
--
Please remember to mention me / in tapes you leave behind.
Oct 8 '08 #34

P: n/a
On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalidwrote:
Ian Collins said:
Nick Keighley wrote:
Well written C compiles with C++. That is a fact.
No it is not. *The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.
a couple of people have said this. Are they C89 constructs?
I'm aware that a fair amount of C99 stuff is unlikely
to make it into C++ (eg. complex numbers).

And they are "well-written" constructs, too.

Nick, are you really saying that adding a cast to a call to a function
returning void * is either badly-written C or legal C++?
er, no.

char *fred = (char*)malloc(42);

is not particularly good C but it will compile with C++.

--
Nick Keighley
Oct 8 '08 #35

P: n/a
Nick Keighley wrote:
On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalidwrote:
>Ian Collins said:
>>Nick Keighley wrote:
>>>Well written C compiles with C++. That is a fact.
No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.

a couple of people have said this. Are they C89 constructs?
Yes, many of them are. See appendix C of the C++ standard. It's 15 pages
long. Many of the constructs are very uncommon, many of them will never
appear in well-written C code. But some of them do occur with moderate
frequency even in well-written C code.
Oct 8 '08 #36

P: n/a
Nick Keighley said:
On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalidwrote:
>Ian Collins said:
Nick Keighley wrote:
>Well written C compiles with C++. That is a fact.
No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.

a couple of people have said this. Are they C89 constructs?
Sure. Several keywords, for a start, and automatic void * conversion.

<snip>
>Nick, are you really saying that adding a cast to a call to a function
returning void * is either badly-written C or legal C++?

er, no.
Of course I got that the wrong way round (sigh). I meant to ask whether you
really thought *not* adding a cast is either badly-written C or legal C++.
char *fred = (char*)malloc(42);

is not particularly good C but it will compile with C++.
We were discussing well-written C, were we not? The well-written equivalent
of the above:

char *buf = malloc(n);

is *not* legal C++.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 8 '08 #37

P: n/a
Peter Nilsson <ai***@acay.com.auwrites:
Flash Gordon <s...@spam.causeway.comwrote:
>Peter Nilsson wrote, On 06/10/08 23:03:
Flash Gordon <s...@spam.causeway.comwrote:
Nick Keighley wrote, On 03/10/08 09:27:
An example of someone who writes code that compiles
with both C and C++ is P.J.Plauger.
Let's not forget Ritchie and Kernighan.

That was because there were no compilers conforming to
ANSI C at the time so they had to use a C++ compiler to
get access to certain features.

<http://groups.google.com/group/comp....ea4a63a610cac?
dmode=source>
In which Bjarne Stroustrup writes:
| Dennis Ritchie and Brian Kernighan are among the most thoughtful of
| people. They did have a choice at the time. If they had thought it
| important/best to leave malloc calls uncast they could have (1) used
| the ANSI C compiler or (2) edited the casts out in the final draft
| (after the final check with the ANSI C compiler) or (3) politely asked
| me for a compatibility feature in Cfront (we talked almost every day).
|
| I think it is safest to assume that when Dennis Ritchie and Brian
| Kernighan did something, it was because they wanted to do that and not
| the opposite.

But the errata list for K&R2 acknowledges that casting the result of
malloc isn't such a good idea after all.
<http://netlib.bell-labs.com/cm/cs/cbook/2ediffs.html>:

142 (section 6.5, toward the end): The remark about casting the
return value of malloc ("the proper method is to declare ... then
explicitly coerce") needs to be rewritten. The example is correct
and works, but the advice is debatable in the context of the
1988-1989 ANSI/ISO standards. It's not necessary (given that
coercion of void * to ALMOSTANYTYPE * is automatic), and possibly
harmful if malloc, or a proxy for it, fails to be declared as
returning void *. The explicit cast can cover up an unintended
error. On the other hand, pre-ANSI, the cast was necessary, and it
is in C++ also.
>>Is he an imbecile or an idiot?
I *think* he was calling the customers dumbos, not the
authors of the library.

Plauger shares the view of his customers. So any criticism
of his customers must be applied to Plauger himself, if
consistency is to hold.

I thought that his view was that it was the right thing for
him to do it because that was his customers' requirement.

<http://groups.google.com/group/comp....11d85b17ce318?
dmode=source>
In which P.J. Plauger, replying to Richard Heathfield, writes:
| I thought I had given more than one reason, en passant, but here's a
| quick review. Indeed the first motivation we had for adding casts to
| malloc calls was to satisfy a market need to have all our Standard C
| library compile either as C or C++. The C++ Standard (thanks to me)
| deliberately permits the C library to have either extern "C" or
| extern "C++" linkage -- and we have serious customers for both
| flavors. Having done so, we then found reasons to make *all* of our
| C source code compilable as C++.
|
| Generally I avoid casts for the reason so often given -- they're so
| strong that they often hide problems. We add them where required for
| correctness, for portability, for C++ compatibility, and to quiet
| silly warnings. Our experience over the years is that the last
| category of casts do indeed raise the cost of maintenance -- we fix
| something here and the forgotten consequences there are masked by
| the cast, until we discover the bug by a painful runtime trace.
|
| But allocator casts often *help* us find bugs that arise during
| maintenance. The classic pattern is a structure declared here,
| containing a pointer to another structure declared somewhere else,
| for which storage is allocated there, and freed some other
| there. That's why we allocate N times the size of the thing we
| really want, cast the resultant pointer to a pointer to that type,
| and store it in what should be a compatible type of pointer. We've
| had the compiler inform us of bugs in both size and pointer types as
| the code changes under maintenance and enhancement.
|
| In our environment, bugs like failing to include stdlib.h get found
| and fixed in the first pass or two of code writing. We generally
| perform *many* passes over our code during development, and develop
| a companion set of tests. So the kind of bugs masked by casts on
| malloc are cheap to fix, while the kind exposed by such casts are
| much more expensive.

But I believe the bugs exposed by casting the result of malloc can be
avoided by using the clc-recommended idiom:

ptr = malloc(COUNT * sizeof *ptr);

even if "ptr" is some more complex expression.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 8 '08 #38

P: n/a
Richard Heathfield <rj*@see.sig.invalidwrites:
Nick Keighley said:
>On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalidwrote:
>>Ian Collins said:
Nick Keighley wrote:
>>Well written C compiles with C++. That is a fact.

No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.

a couple of people have said this. Are they C89 constructs?

Sure. Several keywords, for a start, and automatic void * conversion.
You mean C++ keywords that are valid C89 identifiers, right? On first
reading, I thought you were talking about C keywords.

[...]

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 8 '08 #39

P: n/a
Nick Keighley <nick_keighley_nos...@hotmail.comwrote:
Well written C compiles with C++. That is a fact.
It may be the case that it's correct C but not correct C++, and vice
versa.
Here's one of the best pages I've found on the net about C/C++
differences:
<http://david.tribble.com/text/cdiffs.htm>

Here's some code that doesn't work in C++, but does work in C,

#include <limits.h>

int main(void) {
char m[sizeof 'A'];
return m[CHAR_BIT == 8] = 0;
}

This takes advantage of the following difference, that 'A' in C has
type int, but in C++ has type char.
In C this code always works; in C++ it never works.
Oct 8 '08 #40

P: n/a
vi******@gmail.com writes:
>Nick Keighley <nick_keighley_nos...@hotmail.comwrote:
Well written C compiles with C++. That is a fact.

It may be the case that it's correct C but not correct C++, and vice
versa.
Here's one of the best pages I've found on the net about C/C++
differences:
<http://david.tribble.com/text/cdiffs.htm>

Here's some code that doesn't work in C++, but does work in C,

#include <limits.h>

int main(void) {
char m[sizeof 'A'];
return m[CHAR_BIT == 8] = 0;
}

This takes advantage of the following difference, that 'A' in C has
type int, but in C++ has type char.
In C this code always works; in C++ it never works.
Incorrect. If sizeof(int)==1 (which implies CHAR_BIT>=16), then it
can work in both C and C++.

Sure, there are plenty of contrived examples of code that works in C
but not in C++. Here's another one:

int main(void)
{
#ifdef __cplusplus
#error
#endif
return 0;
}

Such examples are irrelevant to Nick's claim that "Well written C
compiles with C++.", unless you want to claim that either of the above
examples is well written.

Nick's claim is incorrect because well written C does not cast the
result of malloc (and calloc, and realloc). Avoiding that issue
requires writing code that's less than ideal in C for the sake of C++
compatibility. (Avoiding C++ keywords is less of an issue, since well
written C code doesn't *need* to use them as identifiers.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 8 '08 #41

P: n/a
On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.orgwrote:
vipps...@gmail.com writes:
Nick Keighley <nick_keighley_nos...@hotmail.comwrote:
Well written C compiles with C++. That is a fact.
It may be the case that it's correct C but not correct C++, and vice
versa.
Here's one of the best pages I've found on the net about C/C++
differences:
<http://david.tribble.com/text/cdiffs.htm>
Here's some code that doesn't work in C++, but does work in C,
#include <limits.h>
int main(void) {
char m[sizeof 'A'];
return m[CHAR_BIT == 8] = 0;
}
This takes advantage of the following difference, that 'A' in C has
type int, but in C++ has type char.
In C this code always works; in C++ it never works.

Incorrect. If sizeof(int)==1 (which implies CHAR_BIT>=16), then it
can work in both C and C++.
Ah yes, correctly noted.
Sure, there are plenty of contrived examples of code that works in C
but not in C++. Here's another one:

int main(void)
{
#ifdef __cplusplus
#error
#endif
return 0;

}
Unless the implementation defines __cplusplus ;-)
Such examples are irrelevant to Nick's claim that "Well written C
compiles with C++.", unless you want to claim that either of the above
examples is well written.
Depends on what Nick means with well written, but let's not stretch
it, I agree.
Nick's claim is incorrect because well written C does not cast the
result of malloc (and calloc, and realloc). Avoiding that issue
requires writing code that's less than ideal in C for the sake of C++
compatibility. (Avoiding C++ keywords is less of an issue, since well
written C code doesn't *need* to use them as identifiers.)
I also agree.
Oct 8 '08 #42

P: n/a
vipps...@gmail.com wrote:
On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.orgwrote:
....
Sure, there are plenty of contrived examples of code that works in C
but not in C++. Here's another one:

int main(void)
{
#ifdef __cplusplus
#error
#endif
return 0;

}

Unless the implementation defines __cplusplus ;-)
That's not permitted for a conforming implementation ot C99
(6.10.8p5). I think that was permitted in C90, but I'm not sure. It
was never good QoI, at least not at any time since the birth of C++.

Oct 8 '08 #43

P: n/a
vi******@gmail.com writes:
On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.orgwrote:
[...]
>Sure, there are plenty of contrived examples of code that works in C
but not in C++. Here's another one:

int main(void)
{
#ifdef __cplusplus
#error
#endif
return 0;

}

Unless the implementation defines __cplusplus ;-)
[...]

A conforming C99 implementation is not allowed to do so. (C90 doesn't
have this rule.)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Oct 8 '08 #44

P: n/a
Nick Keighley wrote:
On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalidwrote:
>Ian Collins said:
>>Nick Keighley wrote:
>>>Well written C compiles with C++. That is a fact.
No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.

a couple of people have said this. Are they C89 constructs?
Yes, the stricter C++ rules for enums are an obvious example.

--
Ian Collins.
Oct 8 '08 #45

P: n/a
Keith Thompson said:
Richard Heathfield <rj*@see.sig.invalidwrites:
>Nick Keighley said:
>>On 8 Oct, 09:38, Richard Heathfield <r...@see.sig.invalidwrote:
Ian Collins said:
Nick Keighley wrote:

Well written C compiles with C++. That is a fact.

No it is not. The common subset of C and C++ compiles as C and C++.
There are a number of C constructs that are not valid C++.

a couple of people have said this. Are they C89 constructs?

Sure. Several keywords, for a start, and automatic void * conversion.

You mean C++ keywords that are valid C89 identifiers, right?
Yes.
On first reading, I thought you were talking about C keywords.
Lazy phrasing on my part. Sorry.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 9 '08 #46

P: n/a
ja*********@verizon.net said:
vipps...@gmail.com wrote:
>On Oct 8, 8:59 pm, Keith Thompson <ks...@mib.orgwrote:
...
Sure, there are plenty of contrived examples of code that works in C
but not in C++. Here's another one:

int main(void)
{
#ifdef __cplusplus
#error
#endif
return 0;

}

Unless the implementation defines __cplusplus ;-)

That's not permitted for a conforming implementation ot C99
(6.10.8p5).
True, but of little relevance for the time being.
I think that was permitted in C90, but I'm not sure.
It was.
It
was never good QoI, at least not at any time since the birth of C++.
Why is it not good QoI? It is not the job of any programming language to
avoid treading on the toes of another language. Would we criticise an
implementation's QoI for using the identifier ENVIRONMENT (which is
reserved, like __cplusplus) just because it clashes with COBOL?

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 9 '08 #47

P: n/a
Richard Heathfield wrote:
ja*********@verizon.net said:
>vipps...@gmail.com wrote:
>>Unless the implementation defines __cplusplus ;-)
That's not permitted for a conforming implementation ot C99
(6.10.8p5).

True, but of little relevance for the time being.
Now now Richard, some of us do use platforms where the native compiler
is C99.
>It
was never good QoI, at least not at any time since the birth of C++.

Why is it not good QoI? It is not the job of any programming language to
avoid treading on the toes of another language. Would we criticise an
implementation's QoI for using the identifier ENVIRONMENT (which is
reserved, like __cplusplus) just because it clashes with COBOL?
How often does C share system or standard library headers with COBOL?
Try putting #define __cplusplus before #include <stdio.hand see how
far your compiler gets.

--
Ian Collins.
Oct 9 '08 #48

P: n/a
Ian Collins said:
Richard Heathfield wrote:
>ja*********@verizon.net said:
>>vipps...@gmail.com wrote:
>>>Unless the implementation defines __cplusplus ;-)
That's not permitted for a conforming implementation ot C99
(6.10.8p5).

True, but of little relevance for the time being.
Now now Richard, some of us do use platforms where the native compiler
is C99.
Sure - and there are some people who do fly on the Space Shuttle. Tips on
drinking whisky in a zero-g environment will be very useful to *them*, no
doubt, but they are still of little relevance in general terms. When we
have a few million people up in orbit, the relevance of such tips will
increase. And, perhaps a little while after that, C99 might even start
catching on among implementors.
>>It
was never good QoI, at least not at any time since the birth of C++.

Why is it not good QoI? It is not the job of any programming language to
avoid treading on the toes of another language. Would we criticise an
implementation's QoI for using the identifier ENVIRONMENT (which is
reserved, like __cplusplus) just because it clashes with COBOL?
How often does C share system or standard library headers with COBOL?
Been there, done that, not funny. Also beside the point.
Try putting #define __cplusplus before #include <stdio.hand see how
far your compiler gets.
No, I can't do that, because __cplusplus starts with two consecutive
underscores, which means it's reserved for the implementation. I'm tempted
to add "duh!", but I'll try to refrain.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Oct 9 '08 #49

P: n/a
Richard Heathfield wrote:
Ian Collins said:
>Richard Heathfield wrote:
>>ja*********@verizon.net said:
vipps...@gmail.com wrote:
Unless the implementation defines __cplusplus ;-)
That's not permitted for a conforming implementation ot C99
(6.10.8p5).
True, but of little relevance for the time being.
Now now Richard, some of us do use platforms where the native compiler
is C99.

Sure - and there are some people who do fly on the Space Shuttle.
There's rather a lot more Solaris and AIX developers than space shuttle
passengers.
>Try putting #define __cplusplus before #include <stdio.hand see how
far your compiler gets.

No, I can't do that, because __cplusplus starts with two consecutive
underscores, which means it's reserved for the implementation.
You can't, but you might be a compiler implementer who's tempted to add
the define to one of your implementation's headers. Doing so would be a
great way to limit sales.

--
Ian Collins.
Oct 9 '08 #50

101 Replies

This discussion thread is closed

Replies have been disabled for this discussion.