473,899 Members | 3,313 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C99 Question

Hi,

Which section of C99 says that return value
of malloc(3) should not be casted?

Thanks.

--
Vijay Kumar R Zanvar
My Home Page - http://www.geocities.com/vijoeyz/
Nov 14 '05
110 4568
Vijay Kumar R Zanvar wrote:
Which section of C99 says that
the return value of malloc should not be casted?


Good question! The ANSI/ISO C 99 standard does *not* say that
the return value of malloc should not be casted.

I *always* cast malloc's return value

char* p = (char*)malloc(n *sizeof(char));

so that my C++ compiler won't complain.

There is *no* advantage to omitting the cast.
It is purely a style issue
but some C programmers have become fond of this style
and invented various *lame* arguments
to justify their personal aesthetics.

Nov 14 '05 #31
E. Robert Tisdale wrote:
Vijay Kumar R Zanvar wrote:
Which section of C99 says that
the return value of malloc should not be casted?
Good question! The ANSI/ISO C 99 standard does *not* say that
the return value of malloc should not be casted.


It doesn't say you should check the return value of malloc, either.

I *always* cast malloc's return value

char* p = (char*)malloc(n *sizeof(char));

so that my C++ compiler won't complain.
C and C++ are different languages. In C++, you'd be better off doing this:

char *p = new char[n];

unless you wanted to resize the string at some point, in which case you'd be
better off using a std::string.

There is *no* advantage to omitting the cast.


There is no advantage to inserting it. In C99, it is no longer /dangerous/
to insert it, but it's still not a good idea.

--
Richard Heathfield : bi****@eton.pow ernet.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
Nov 14 '05 #32
Randy Howard wrote:
Sorry about my brief relapse into my native tongue (Dutch). Figured out
this would perhaps get the message across to our Italian friend.
You may notice that if you rot13 my last message, it seems familiar
somehow.


I noticed, but it seems to yield a statement in Dutch, partially
defending the dubious practice of malloc casting. In order to follow the
clc party line, I think it's wiser to leave that rot13'ed I'd say.

More importantly, I failed to come up with a witty thing to say about
rot13 that would look like anything other than me being smug about
spotting it.

Can't say I didn't try though; I will never look at guys named "Benny"
in quite the same way :-)

Best regards,

Sidney

Nov 14 '05 #33
On Tue, 30 Dec 2003 12:42:42 +0200
"lallous" <la*****@lgwm.o rg> wrote:
Hello,
"Richard Heathfield" <in*****@addres s.co.uk.invalid > wrote in message
news:3f******@n ews2.power.net. uk...
Vijay Kumar R Zanvar wrote:
The malloc function - Just Don't Cast.

This might be silly from me, but you mean don't cast as:
int *i = (int *) malloc(sizeof(i nt));
?
What other solutions are there then? just assign w/o casting?


Yes. The generally recommended way to use malloc around here is

#include <stdlib.h>

/* lots of stuff */

derf = malloc( N * sizeof *derf );

Where N is the number of objects you want derf to point.

If your compiler complains about the above (given appropriate
definitions of derf and N) then you are not invoking it correctly or I
have made a trypo.
--
Flash Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spam, it is real and I read it.
Nov 14 '05 #34
CBFalconer <cb********@yah oo.com> wrote:
Richard Bos wrote:
No. The _big_ advantage of not casting malloc() is that you have
several fewer useless casts in your program, just as the big
advantage of not hanging a high voltage sign on batteries is that
you're not carrying several high voltage signs for your mobile
phone et cetera. Both also have other advantages (you will be
warned if you forget <stdlib.h>; you won't be hampered when you
try to use your phone), but the main advantage is that the fewer
useless warning signals, the more attention you will pay if you
really _are_ doing something awkward involving pointers - or if
you really are in danger of being electrocuted.


And it also encourages you to treat the presence of ANY cast as an
indication of a potential problem. There are very few places they
are really necessary, with calls to variadic functions heading my
list.


The only places I can think of where you'd need them in code I encounter
more or less regularly are variadic functions (usually only those calls
involving null pointer constants), <ctype.h> functions, and helper
functions for qsort() and the like. In all those three cases, there is a
good and clear reason for the cast; in the first and last cases, I'd
even say the cast makes sense, and in the second case, it is awkward,
but inevitable.
Sadly, most of the casts I see in code not my own are completely
superfluous, and most of those involve void *s.

Richard
Nov 14 '05 #35
"E. Robert Tisdale" <E.************ **@jpl.nasa.gov > wrote:
I *always* cast malloc's return value

char* p = (char*)malloc(n *sizeof(char));

so that my C++ compiler won't complain.


Then you're a bad C++ programmer, and not a C programmer at all. But you
knew that, right?

Richard
Nov 14 '05 #36
Richard Heathfield <do******@addre ss.co.uk.invali d> wrote:
E. Robert Tisdale wrote:
There is *no* advantage to omitting the cast.


There is no advantage to inserting it. In C99, it is no longer /dangerous/
to insert it, but it's still not a good idea.


Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.

Richard
Nov 14 '05 #37
begin followup to Richard Bos:
Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.


Let's see if I understand this right.
The danger is that the diagnostic

initialization makes pointer from integer without a cast

is mandatory for a conforming compiler, while

implicit declaration of function `malloc'

is not.
All together it takes three things to actually fall into the trap:

1. Casting the return value of _every_ malloc
2. Omitting #include <stdlib.h>
3. Compiling without warnings

Well, yes, probably a lot of newbies actually do this.
But on the other hand of the spectrum are people that use C++ as a
kind of lint, i.e. a stricter syntax checking.

--
Für Google, Tux und GPL!
Nov 14 '05 #38
Alexander Bartolich wrote:
begin followup to Richard Bos:
Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.


Let's see if I understand this right.
The danger is that the diagnostic

initialization makes pointer from integer without a cast

is mandatory for a conforming compiler, while

implicit declaration of function `malloc'

is not.


Not in C99 (which is the scenario under consideration), because implicit
function declarations were removed in C99.

I think Richard Bos is making a valid *philosophical* point. The cast
remains inadvisable, even though in C99 it will no longer mask the omission
of <stdlib.h>. I agree with him that the cast is inadvisable, but I'd
hesitate to use the word "dangerous" in a C99 context.

--
Richard Heathfield : bi****@eton.pow ernet.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
Nov 14 '05 #39
Alexander Bartolich <al************ *****@gmx.at> writes:
begin followup to Richard Bos:
Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.
Let's see if I understand this right.
The danger is that the diagnostic

initialization makes pointer from integer without a cast

is mandatory for a conforming compiler,


A conforming compiler doesn't have to emit exactly that text, of course,
but it must emit some kind of diagnostic if a pointer is initialized with
an integer (other than a null pointer constant) or an integer (other than
a null pointer constant) is assigned to a pointer.
while

implicit declaration of function `malloc'

is not.
Yes, a conforming compiler is not required to emit a diagnostic if a
function is used without prior declaration.
All together it takes three things to actually fall into the trap:

1. Casting the return value of _every_ malloc
2. Omitting #include <stdlib.h>
3. Compiling without warnings

Well, yes, probably a lot of newbies actually do this.
But on the other hand of the spectrum are people that use C++ as a
kind of lint, i.e. a stricter syntax checking.


I consider people who compile C code with a C++ compiler to be quite at
the newbie end of the spectrum.

Martin
Nov 14 '05 #40

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

Similar topics

1
3109
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
3
5051
by: Stevey | last post by:
I have the following XML file... <?xml version="1.0"?> <animals> <animal> <name>Tiger</name> <questions> <question index="0">true</question> <question index="1">true</question> </questions>
7
2675
by: nospam | last post by:
Ok, 3rd or is it the 4th time I have asked this question on Partial Types, so, since it seems to me that Partial Types is still in the design or development stages at Microsoft, I am going to ask it differently. FOUR QUESTIONS: The background: I got three (3) files
3
3105
by: Ekqvist Marko | last post by:
Hi, I have one Access database table including questions and answers. Now I need to give answer id automatically to questionID column. But I don't know how it is best (fastest) to do? table before rowID answID qryrow questionID datafield 1591 12 06e 06e 06e question 1593 12 06f 06f 06f question 1594 12 answer to the question 06f
10
3453
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a database or continue to process on to the next page. I am now trying to learn ASP to see if we can replace some of our applications that were written in php with an ASP alternative. However, after doing many searches on google and reading a couple...
10
3759
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server Error in '/QuickStartv20' Application. -------------------------------------------------------------------------------- Configuration Error Description: An error occurred during the processing of a configuration file
53
4111
by: Jeff | last post by:
In the function below, can size ever be 0 (zero)? char *clc_strdup(const char * CLC_RESTRICT s) { size_t size; char *p; clc_assert_not_null(clc_strdup, s); size = strlen(s) + 1;
56
4848
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
2
4301
by: Allan Ebdrup | last post by:
Hi, I'm trying to render a Matrix question in my ASP.Net 2.0 page, A matrix question is a question where you have several options that can all be rated according to several possible ratings (from less to more for example). I have a question object that has two properties that contain the collections Options and Ratings. now I want this kind of layout: --- Rating1 Rating2 Rating3 Option 1 () () ...
3
2567
by: Zhang Weiwu | last post by:
Hello! I wrote this: ..required-question p:after { content: "*"; } Corresponding HTML: <div class="required-question"><p>Question Text</p><input /></div> <div class="not-required-question"><p>Question Text</p><input /></div>
0
9843
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
11272
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
10863
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
10494
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
9666
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
8039
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7201
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
6081
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3317
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.