473,847 Members | 2,041 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting the return value of malloc() ?

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
101 4379
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
In article <7c************ *************** *******@p49g200 0hsd.googlegrou ps.com>,
Tinkertim <ti*******@gmai l.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
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
On 2 Oct, 10:22, Tinkertim <tinker...@gmai l.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
On 2 Oct, 10:59, Nick Keighley <nick_keighley_ nos...@hotmail. com>
wrote:
On 2 Oct, 10:22, Tinkertim <tinker...@gmai l.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
polas said:

<snip>
As far as I understood it (which might be somewhat wrong) actually
casting the return value is unwanted.
If you mean "unnecessar y", 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
On 2 Oct, 13:12, Richard Heathfield <r...@see.sig.i nvalidwrote:
polas said:

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

If you mean "unnecessar y", 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
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...@gmai l.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
Tinkertim <tinker...@gmai l.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

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

231
23304
by: Brian Blais | last post by:
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?
33
2298
by: hermit_crab67 | last post by:
Can someone explain to a C newbie why this doesn't work as I expect it to work? (expectations clearly outlined in the printf statement in main routine) OS: Linux 2.4.26 GCC: 2.95.4 void modify_pointer(char *); int main(int argc, char *argv) {
35
2720
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
14
2658
by: Mirko | last post by:
Hello, I'm new to this list and to Usenet in general, so please forgive (and advice) me, if I do something wrong. Anyway. I am a bit confused, because I always thought one _should_ explicitly cast the void* pointer returned by malloc. Now I read postings saying that this is dangerous. Could somebody please clearify this?
8
9414
by: Neha | last post by:
Hi all Its seems bit silly que but pleasee explan me why this error is coming ? and what will be the solution if i want void * to be intilaize by struct * and this code is puerly in C. -- #include <stdlib.h> #include <stdio.h>
41
4984
by: SRR | last post by:
Why is it discouraged to explicitly typecast the void pointer returned by malloc(); function? For example: { int *p; p = (int*)malloc(2*sizeof(int)); /*Explicit casting is done, therfore it is said to be a bad practice*/ /*Some codes*/ }
17
2237
by: sophia.agnes | last post by:
Hi , I was going through peter van der linden's book Expert C programming, in this book there is a section named "How and why to cast" the author then says as follows (float) 3 - it's a type conversion and the actual bits change. if you say (float) 3.0 it is a type disambiguation,and the compiler can plant the correct bits in the first place.some people say that
32
2400
by: alex.j.k2 | last post by:
Hello all, I have "PRECISION" defined in the preprocessor code and it could be int, float or double, but I do not know in the code what it is. Now if I want to assign zero to a "PRECISION" variable, which of the following lines are correct:
0
9887
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, weíll explore What is ONU, What Is Router, ONU & Routerís main usage, and What is the difference between ONU and Router. Letís take a closer look ! Part I. Meaning of...
0
9730
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10984
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10650
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10342
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7056
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5720
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5912
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3164
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.