Casting the return value of malloc() ?

T

Tinkertim

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
 
I

Ian Collins

Tinkertim said:
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.
 
K

Kenny McCormack

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

Nick Keighley

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

polas

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
 
P

polas

polas said:



If you mean "unnecessary", you're right.


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.


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
 
N

Nick Keighley

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
 
C

CBFalconer

Nick said:
.... snip ...

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

Not library writers. That would be an excellent way of installing
library bugs. However some people want to sell their software,
written in C source, to imbeciles who will simply compile it and
then use it. They want this to work even though the idiots are
using a C++ compiler. After all, why have a support call? Without
it the dumbos are happy, and the selling firm makes more money.
 
P

Peter Nilsson

Tinkertim said:
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.
 
K

Kenny McCormack

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

Flash Gordon

Nick Keighley wrote, On 03/10/08 09:27:
In general library writers do not have to write code (apart from
possibly headers) so that it compiles as both C and C++ to make the
library available for use from both C and C++. Distribute build scripts
that will build it as C for most common implementations and, in general
(but not always) the problem is installed.
complete bollocks

Well, it can lead to some bugs where the languages are subtly different.
wow. imagine that people actually want to compile the source library
they bought/down loaded. And then they want to use it! I'd always
thought people bought source code so they could recycle it as
toilet paper.

That does not require the code to be compilable in multiple languages.
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.

Yes, it is true.
do you normally refer to customers as idiots?
I assume you are a hobbyist programmer that doesn't actually have
to deal with real-world customers and suppliers.

I've been known to call customers idiots because some are, I just don't
do it where the customers can here me!
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?

I *think* he was calling the customers dumbos, not the authors of the
library.

I agree that there are sometimes good commercial reasons to produce code
that compilers as either language and works properly whichever language
is used. I just don't think it is really that common a requirement. I
think most people will be happy if a build script (makefile, batch file,
project file or whatever) is provided that build it appropriately and
header files that work and won't care what language it is compiled as.
 
C

CBFalconer

Flash said:
I *think* he was calling the customers dumbos, not the authors of
the library.

Exactly. And C library code is easily configured to be usable in
C++ systems, via the __cpluplus__ identifier. It still needs to be
compiled as C code, but can be linked into C++ systems. What more
do you really want?
 
K

Keith Thompson

CBFalconer said:
Exactly. And C library code is easily configured to be usable in
C++ systems, via the __cpluplus__ identifier. It still needs to be
compiled as C code, but can be linked into C++ systems. What more
do you really want?

It's *also* possible to write code in the intersection of C and C++,
code that will behave correctly whether compiled with a C compiler or
with a C++ compiler. This can be useful if your customers doesn't
just need to call your code through the interfaces you've provided,
but to grab snippets to incorporate into their own C or C++ code
(assuming the license allows this).

Writing code that works properly both as C and as C++ requires some
care -- care that P.J. Plauger is eminently qualified to exercise.
But then, just writing code that works properly and portably in C
requires very nearly as much care.

The actual need to write code that's valid as both C and C++ is fairly
rare, but it's not nonexistent. If you want to disagree, that's fine
-- but you'll need better arguments than calling the customers
"dumbos".
 
F

Flash Gordon

Keith Thompson wrote, On 04/10/08 01:26:
I stated it was possible in the post you replied to, although I did not
specify the mechanism. I know the mechanism, it just was not relevant. I
said that the prefered way of distribution it as source would be to
include build scripts which invoke a compiler for the correct language
and that in my opinion this covers most requirements.
It's *also* possible to write code in the intersection of C and C++,
code that will behave correctly whether compiled with a C compiler or
with a C++ compiler. This can be useful if your customers doesn't
just need to call your code through the interfaces you've provided,
but to grab snippets to incorporate into their own C or C++ code
(assuming the license allows this).

It is also useful if customer A will pay you _small_fortune_ for the
code explicitly requiring that it be C++ code and customer B will pay
you _small_fortune_ for the code explicitly requiring that it is C code.
Remember that neither customer will care about the other customers
requirements. Remember also that a lot of people are writing code for
money, so if customers want to pay enough we will do things the hard
ways, especially if the alternative is greatly reduced profits.
Writing code that works properly both as C and as C++ requires some
care -- care that P.J. Plauger is eminently qualified to exercise.
But then, just writing code that works properly and portably in C
requires very nearly as much care.

The actual need to write code that's valid as both C and C++ is fairly
rare, but it's not nonexistent. If you want to disagree, that's fine
-- but you'll need better arguments than calling the customers
"dumbos".

In my opinion the commercial argument for writing code that is valid and
correct as both languages is valid even if the customers *are* "dumbos".

If what the customer wants is legal (in the sense of no laws being
broken), possible, something you don't have a moral objection to, and
something you can do profitably, then it can be the right thing to do
even if there are better technical solutions.
 
O

Old Wolf

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

Keith Thompson

Old Wolf said:
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.
 
I

Ian Collins

Old said:
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.
 
R

Richard Bos

True, but in the general case they'll be both bad C and worse C++.
_Correct_, yes, but horrible style.
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
 
K

Keith Thompson

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.

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

Ask a Question

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

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

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,571
Members
45,045
Latest member
DRCM

Latest Threads

Top