Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C Programming > Casting return of malloc

Reply
Thread Tools

Casting return of malloc

 
 
Peter Nilsson
Guest
Posts: n/a
 
      02-09-2005
> Ben Pfaff <(E-Mail Removed)> writes:
> > "(E-Mail Removed)" <(E-Mail Removed)> writes:
> >
> > > 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.

> >
> > I don't recommend casting the return value of malloc():
> >
> > * The cast is not required in ANSI C.
> >
> > * Casting its return value can mask a failure to #include
> > <stdlib.h>, which leads to undefined behavior.


Not casting malloc can also mask undefined behaviour, though to
a significantly lesser degree. Nonetheless, the possibility
exists and has even been demonstrated by newbies posting to
clc.

Keith Thompson wrote:
>
> Some C90 compilers, and all conforming C99 compilers, will warn about
> this anyway. (That's certainly not an argument in favor of casting,
> of course.)


Actually, it is. As I've said before, the malloc casting issue
is just a small component of a much bigger issue that has been
recognised by C programmers and implementors for a long time.

I'd be curious to know how many conforming hosted implementations
don't offer the facility of a warning for the use of an unprototyped
function. [There are countless implementations which do offer this.]

> > * If you cast to the wrong type by accident, odd failures can
> > result.
> >
> > Some others do disagree, such as P.J. Plauger (see article
> > <9sFIb.9066$(E-Mail Removed)>).

>
> I don't know that he necessarily disagrees; he just happens to work

in
> an unusual environment where casting the result of malloc() makes
> sense. I don't think he would argue that *everyone* should cast the
> result of malloc(). (I can't find that message-id on Google; are you
> sure it's correct?)


Plauger's exact words:

>From the thread...


http://groups-beta.google.com/group/...9404794117b276

"Nor did I ever promote casting malloc as general good C practice.
I merely pointed out (repeatedly) that the opposition to casting
malloc has become kneejerk in this forum. I have an active dislike
for any dogma that replaces thought. IM(extensive)E I've encountered
several occasions where it makes good sense to add the casts, and
I tried to describe one or two of them. The kneejerks took these
descriptions as attacks on their beloved style rule (which they
were not), and as rival dogma (which it is not).

"FWIW, I would advise most C programmers *not* to cast malloc calls,
for most of the reasons advanced by others in this forum"

-

"[Good C programing is] defined in relation to the C Standard
*and the requirements of a given programming project*. Nothing
in the C Standard says you should format your code neatly. And
nothing says you shouldn't. Yet it is a poor project that has
no rules about code layout. Religious wars have been fought for
decades over the proper placement of braces, in part because
there's often really no compelling reason to favor one scheme
over another -- it all depends on what weights you give a handful
of layout principles. (Again FWIW, I pioneered one of the now
popular styles, known as the Whitesmiths style, but I myself
don't adhere to it slavishly.)

"It is a curious failing of techies that they mistake *all*
their opinions as the product of rational thought. We all
think with our hormones from time to time; it really helps to
notice when you're doing so. IME, the zeal with which a techie
defends a debatable opinion varies inversely with its rational
defensibility.

"Put your casts, and your braces, where you may. But do please
try to think, from time to time, about *why* you're doing what
you're doing. More to the point, when somebody comes up with
a different set of style rules, consider the possibility that
they might not be completely misguided. You might learn
something."

-

>From the thread...


http://groups-beta.google.com/group/...50634cd1717953

-

"... I'm *not* advocating this position to C programmers in general.
I've merely been defending why it might sometimes be a reasonable
position for some C programmers in some contexts. The only thing I
really can't stand is intolerance. ..."

-

"...All I'm holding out for, and all I've asked for from the
beginning, is for people to recognize that:

"1) Style rules should be developed by considering all applicable
principles and weighing their various importance *for that particular
rule*.

"2) Well meaning people can have good reasons for giving different
weights and hence coming up with different style rules."

-

"... The brouhaha over
casting void pointers stems from the fact that the C committee
chose to recycle the existing C++ notation for void pointers and
intentionally gave them different semantics. We did a similar
thing with const and with function prototypes. Thus, the C
committee is partly to blame for the subtle dialect differences
between two languages that have an otherwise broad common base.

"You can pretend that C++ doesn't exist, or that any matters
C++ are OT here, but that's sticking your head in the sand.
The observable fact is that *many* shops that use C mix it on
a daily basis with C++. Yes, you can ghettoize the two to a
large extent by using extern "C" to communicate between functions
written in the different languages. That's a good discipline
that often does the job. Nevertheless, there are cases where it
makes good project sense to maintain some code in the common
dialect that C and C++ share. That dialect is not bastard and
it is not crippled. Those who try to banish it are, IMO, simply
being silly.

"I have no trouble with silliness in most contexts, being silly
about certain issues quite often myself. But I believe it does
a disservice to the lurkers on this newsgroup who are trying
to get educated. They at least deserve a more open consideration
of tradeoffs."

-

[I'm surprised Ben hasn't added this to his sig file...]

>From the thread...


http://groups-beta.google.com/group/...8ead3b6d21c16c

"Make sure you're free from sin before you cast the first malloc."

--
Peter

 
Reply With Quote
 
 
 
 
Randy Howard
Guest
Posts: n/a
 
      02-09-2005
In article <cub5ha$hjc$(E-Mail Removed)>, http://www.velocityreviews.com/forums/(E-Mail Removed)
says...
> Michael Mair wrote:
>
> > This is comp.lang.c;
> > C++ compilers cannot compile many standard conforming C programs

>
> C++ compiler can compile *most* standard conforming C programs.


This can be shown as naive by simply modifying hello world thusly..

#include <stdio.h>
#include <string.h>

int main(void)
{
size_t new; /* this is a new loop variable */
char delete[] = "Hello world!"; /* this is going away after CS101 */

for (new = 0; new < strlen(delete); new++)
{
putchar(delete[new]);
}
putchar('\n');

/* ToDo: Use 'class', 'namespace', 'private', 'protected',
* 'template', 'typeid', 'typename', 'virtual', etc. later on
*/
return 0;
}

gcc -Wall -W eats this with no errors on a hello.c file.

MSVC on the same file called hello.cpp bails after a LONG list
of garbage error messages, the last of which is the immensely
comforting:

fatal error C1003: error count exceeds 100; stopping compilation

Wow. I'd say that is a pretty simple program, surely that isn't
the only one that we can come up with that won't compile with
a C++ compiler.

--
Randy Howard (2reply remove FOOBAR)
"Making it hard to do stupid things often makes it hard
to do smart ones too." -- Andrew Koenig
 
Reply With Quote
 
 
 
 
Ben Pfaff
Guest
Posts: n/a
 
      02-09-2005
Randy Howard <(E-Mail Removed)> writes:

> In article <cub5ha$hjc$(E-Mail Removed)>, (E-Mail Removed)
> says...
>> Michael Mair wrote:
>>
>> > This is comp.lang.c;
>> > C++ compilers cannot compile many standard conforming C programs

>>
>> C++ compiler can compile *most* standard conforming C programs.

>
> This can be shown as naive by simply modifying hello world thusly..


I don't think that any single example of a C program that is not
a C++ program sheds any light on whether "most" standard
conforming C programs are also C++ programs. That could only be
demonstrated via a survey of standard conforming C programs.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
 
Reply With Quote
 
Dave Vandervies
Guest
Posts: n/a
 
      02-09-2005
In article <(E-Mail Removed)>,
Ben Pfaff <(E-Mail Removed)> wrote:

>I don't think that any single example of a C program that is not
>a C++ program sheds any light on whether "most" standard
>conforming C programs are also C++ programs. That could only be
>demonstrated via a survey of standard conforming C programs.


A quick look at a the code for a nontrivial system I'm working with
at WeBuildRadar reveals that about a third of our C source files
are autogenerated and every single one of the rest can be shown with
very brief look to not be valid C++. (A lot of them have assorted
system-specific stuff that makes them not CLC-compliant C either, but
that still leaves a sizeable chunk of valid-C-but-not-valid-C++.)

I can't claim that this is a representative sample, but I suspect that
most other nontrivially sized collections of real C code would yield
similar results. Anybody else willing and able to take a look around
and share their findings?


dave

--
Dave Vandervies (E-Mail Removed)
Fortunately, some of my guys managed to not tell the PHB that he was
doing it right when he was doing it over.
--BAH in comp.arch
 
Reply With Quote
 
E. Robert Tisdale
Guest
Posts: n/a
 
      02-09-2005
Randy Howard wrote:

> E.Robert.Tisdale wrote:
>
>>C++ compiler can compile *most* standard conforming C programs.

>
> This can be shown as naive by simply modifying hello world thusly..


> cat main.c

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) {
// this is going away after CS101
char delete[] = "Hello world!";

for (size_t new = 0; new < strlen(delete); ++new) {
putchar(delete[new]);
}
putchar('\n');

// ToDo: Use 'class', 'namespace', 'private',
// 'protected', 'template', 'typeid', 'typename',
// 'virtual', etc. later on
return 0;
}

> gcc -Wall -std=c99 -pedantic -o main main.c
> ./main

Hello world!
> cat main.cc

#define new C_new
#define delete C_delete
#define class C_class
#define namespace C_namespace
#define private C_private
#define protected C_protected
#define template C_template
#define typeid C_typeid
#define typename C_typename
#define virtual C_virtual
// etc.

#include "main.c"

> g++ -Wall -ansi -pedantic -o main main.cc
> ./main

Hello world!

> gcc -Wall -W eats this with no errors on a hello.c file.
>
> MSVC on the same file called hello.cpp bails
> after a LONG list of garbage error messages,
> the last of which is the immensely comforting:
>
> fatal error C1003: error count exceeds 100; stopping compilation
>
> Wow. I'd say that is a pretty simple program,
> surely that isn't the only one that we can come up with
> that won't compile with a C++ compiler.


It compiles just fine for me.
Can you come up with a better example?
Hint: try one where the compiler doesn't complain.
 
Reply With Quote
 
Ben Pfaff
Guest
Posts: n/a
 
      02-09-2005
(E-Mail Removed) (Dave Vandervies) writes:

> In article <(E-Mail Removed)>,
> Ben Pfaff <(E-Mail Removed)> wrote:
>
>>I don't think that any single example of a C program that is not
>>a C++ program sheds any light on whether "most" standard
>>conforming C programs are also C++ programs. That could only be
>>demonstrated via a survey of standard conforming C programs.

>
> A quick look at a the code for a nontrivial system I'm working with
> at WeBuildRadar reveals that about a third of our C source files
> are autogenerated and every single one of the rest can be shown with
> very brief look to not be valid C++.


I seem to recall another informal survey a while back that
produced similar conclusions.
--
"The lusers I know are so clueless, that if they were dipped in clue
musk and dropped in the middle of pack of horny clues, on clue prom
night during clue happy hour, they still couldn't get a clue."
--Michael Girdwood, in the monastery
 
Reply With Quote
 
E. Robert Tisdale
Guest
Posts: n/a
 
      02-09-2005
Dave Vandervies wrote:

> Ben Pfaff wrote:
>
>>I don't think that any single example of a C program
>>that is not a C++ program sheds any light on whether
>>"most" standard conforming C programs are also C++ programs.
>>That could only be demonstrated
>>via a survey of standard conforming C programs.

>
> A quick look at a the code for a nontrivial system
> [that] I'm working with at WeBuildRadar reveals that
> about a third of our C source files are autogenerated
> and every single one of the rest can be shown with very brief look


Can you be more specific about how you can to this conclusion?
Did you actually attempt to compile any of this C code
with an ANSI/ISO compliant C++ compiler?

> to not be valid C++. (A lot of them have assorted system-specific stuff
> that makes them not CLC-compliant C either
> but that still leaves a sizeable chunk of valid-C-but-not-valid-C++.)
>
> I can't claim that this is a representative sample but I suspect that
> most other nontrivially sized collections of real C code
> would yield similar results.
> [Is] Anybody else willing and able
> to take a look around and share their findings?

 
Reply With Quote
 
E. Robert Tisdale
Guest
Posts: n/a
 
      02-09-2005
Ben Pfaff wrote:

> Dave Vandervies writes:
>
>>Ben Pfaff wrote:
>>
>>>I don't think that any single example of a C program that is not
>>>a C++ program sheds any light on whether "most" standard
>>>conforming C programs are also C++ programs. That could only be
>>>demonstrated via a survey of standard conforming C programs.

>>
>>A quick look at a the code for a nontrivial system I'm working with
>>at WeBuildRadar reveals that about a third of our C source files
>>are autogenerated and every single one of the rest can be shown with
>>very brief look to not be valid C++.

>
> I seem to recall another informal survey a while back
> that produced similar conclusions.


Were these results published?
Can you cite and/or quote them for us?
 
Reply With Quote
 
Randy Howard
Guest
Posts: n/a
 
      02-09-2005
In article <cubrlk$t0s$(E-Mail Removed)>, (E-Mail Removed)
says...
> > gcc -Wall -std=c99 -pedantic -o main main.c
> > ./main

> Hello world!
> > cat main.cc

> #define new C_new
> #define delete C_delete
> #define class C_class
> #define namespace C_namespace
> #define private C_private
> #define protected C_protected
> #define template C_template
> #define typeid C_typeid
> #define typename C_typename
> #define virtual C_virtual
> // etc.
>
> #include "main.c"


Typical trollsdale selective editing disorder. Be sure and let me know
when you have a generic preprocesing tool that will convert *ALL*
C code that has any symptoms like those in the earlier example to compilable
C++ with no errors.

--
Randy Howard (2reply remove FOOBAR)
"Making it hard to do stupid things often makes it hard
to do smart ones too." -- Andrew Koenig
 
Reply With Quote
 
Peter Nilsson
Guest
Posts: n/a
 
      02-09-2005
Michael Mair wrote:
> E. Robert Tisdale wrote:
> > ...snip...
> > [A configured] compiler gives ample diagnostics
> > should you fail to #include <stdlib.h>
> > which defines malloc(size_t) and size_t.

>
> All of your errors and one warning come from your failure to #include
> <stddef.h>, only one warning from the use of malloc() without

prototype
> in scope.


It's a significant warning...

> Many people unfortunately ignore warnings.


And?

The point is professional programmers can and *do* turn on this
warning (and not *JUST* to avoid malloc casting issues,) precisely
to pick up potential bugs that are not picked up by constraint
violation diagnostics.

> > On[e] good reason for casting malloc(int) to the desired type
> > is so you can compile with a C++ compiler:

>
> [snip]
>
> This is comp.lang.c;


And it's a usenet group. What's your point?

> C++ compilers cannot compile many standard conforming C
> programs as C and C++ are different languages.


Different language or not, they share a common subset of
conforming programs. Do you think that subset is OT in clc?
If so, then Plauger is correct is asserting that clc is doing
it's readers a disservice.

> Apart from a select few exceptions,


A few? I wasn't aware clc regulars accepted more than one, and
that with some reluctance.

> mixing of C and C++ is unnecessary and unnecessarily dangerous.


Do you think that not casting malloc is _without_ danger? If so,
you would be a little naive. The central argument is not about
absolute correctness but a question of degrees of robustness.

The weakening of void *'s type in C was deliberate and brought
about by a number of issues of the day. But whatever the reasons,
it came at a cost of robustness. That is true irrespective of
whether we are talking about malloc casting or not.

> C++ specified an interface to C for a very good reason.


The interface does not preclude the C headers from requiring C++
conformance.

The fact that most C programmers put this 'interface' in their
C headers, rather than their C++ source, suggests that C
programmers _are_ generally aware of C++ when writing C. [C99
made mention of __cplusplus precisely because of existing
practice.]

Going further to make C source C++ conforming is generally
not that big a step. Whilst the void * pointer affords C a
mechanism for 'generic' programming, outside of functions like
qsort, memset, etc..., how many C programmers actually sieze on
that? My exposure to C programs suggests comparitavely few.
Those that want generic code generally switch to the template
mechanisms of C++.

Casts in C++ are even more shunned than they are in C. Moreover,
void pointers have little to no use in C++. Had C++ shared the
void pointer type weakness of C, I think C++ would not have
lost any of it's primary strengths, but it would have gained
significant compatibility with C. Bjarne has recognised this
(along with many other possibilities) in his writings.

What I'm getting at is that the 'interface' to C in C++ is
not a _good_ reason to avoid compiling C programs using C++
compilers.

That said, there probably isn't any really good technical
reason to compile C programs under C++, but that doesn't
mean that clc should blind itself to the fact that it is
a very common (and very old) practice.

CLC was, and always has been, an esoteric group. Nonetheless,
there is still a real world out there, no matter how crazy
it might appear. In any case, clc postings can certainly
remain topical without pretending that C++ doesn't (or
shouldn't) exist in the minds of C programmers.

--
Peter

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: How to check whether malloc has allocated memory properly in caseif malloc(0) can return valid pointer Gene C Programming 0 12-20-2010 05:33 AM
Casting the return value of malloc() ? Tinkertim C Programming 82 10-20-2008 12:45 AM
Malloc/Free - freeing memory allocated by malloc Peter C Programming 34 10-22-2004 10:23 AM
free'ing malloc'd structure with malloc'd members John C Programming 13 08-02-2004 11:45 AM
Re: free'ing malloc'd structure with malloc'd members ravi C Programming 0 07-30-2004 12:42 PM



Advertisments