Casting return of malloc

P

Peter Nilsson

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 said:
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.]
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/comp.lang.c/browse_frm/thread/cdbf2a6b0cd13543/8e9404794117b276

"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/comp.lang.c/browse_frm/thread/1504e453be383ee3/f950634cd1717953

-

"... 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/comp.lang.c/browse_frm/thread/d5fdcfbf28848536/028ead3b6d21c16c

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

Randy Howard

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

Ben Pfaff

Randy Howard said:
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.
 
D

Dave Vandervies

Ben Pfaff said:
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
 
E

E. Robert Tisdale

Randy said:
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.
 
B

Ben Pfaff

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

E. Robert Tisdale

Dave said:
Ben said:
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?
 
E

E. Robert Tisdale

Ben said:
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?
 
R

Randy Howard

#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.
 
P

Peter Nilsson

Michael said:
E. Robert Tisdale said:
...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.
 
C

CBFalconer

Peter said:
.... snip ...

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.

How? You can't dereference a void*. You can't add to it. All you
can really do is pass it around (through systems that neither know
nor care what it really represents) until it gets somewhere that
does know and care.

Until you start casting.
 
P

Peter Nilsson

CBFalconer said:

You point the way...
You can't dereference a void*. You can't add to it. All you
can really do is pass it around (through systems that neither know
nor care what it really represents) until it gets somewhere that
does know and care.

Even if the destination 'cares', what guarantee does the language
give you that it can 'know'? It's up to the programmer to make sure
that an X* to void* gets converted back to X* and not Y*.
Until you start casting.

int compare(const void *lhs, const void *rhs)
{
const long *l = lhs;
const long *r = rhs;
return (*l > *r) - (*l < *r);
}

long a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };

qsort(a, sizeof a / sizeof *a, sizeof *a, compare); /* fine */
qsort(b, sizeof b / sizeof *b, sizeof *b, compare); /* boom */
 
R

Richard Bos

E. Robert Tisdale said:
Joona said:
ytrama said:
I have read in one old posting that
[you shouldn't] cast [the] pointer which is returned by malloc.
I would like to know the reason.

It won't fix anything
but it may make the compiler think problems are fixed
when they really aren't.
That's *not* true.

It's not necessarily true for all compilers, but the risk is too great
to ignore.
f.c: In function `f':
f.c:2: warning: implicit declaration of function `malloc'
The compiler gives ample diagnostics

The compiler _may_ give ample diagnostics. Without the cast, it _must_.

(And anyway, superfluous casts are harmful to the mind of the
programmer, and an irritant to the clueful maintainer.)

Richard
 
R

Richard Bos

(You don't even need the &rnum=1 part, btw. And I suggest using .co.uk
instead of .com, to avoid the indefinitely and possibly irrepairably
broken Google Groups Beta.)
Frankly, I believe Trollsdale knew that.

Frankly, I don't have that much confidence in his competence in _any_
field, let alone C or the 'net.

Richard
 
C

CBFalconer

Peter said:
CBFalconer said:

You point the way...
You can't dereference a void*. You can't add to it. All you
can really do is pass it around (through systems that neither know
nor care what it really represents) until it gets somewhere that
does know and care.

Even if the destination 'cares', what guarantee does the language
give you that it can 'know'? It's up to the programmer to make sure
that an X* to void* gets converted back to X* and not Y*.
Until you start casting.

int compare(const void *lhs, const void *rhs)
{
const long *l = lhs;
const long *r = rhs;
return (*l > *r) - (*l < *r);
}

long a[] = { 1, 2, 3 };
int b[] = { 1, 2, 3 };

qsort(a, sizeof a / sizeof *a, sizeof *a, compare); /* fine */
qsort(b, sizeof b / sizeof *b, sizeof *b, compare); /* boom */

I just deleted an answer that wasn't working out. Your other
choice is to write the qsort code yourself, and build the sortable
type into it. Then the compiler will catch misuse. In fact this
is often the best move for both safety and efficiency reasons. The
penalty is that you are no longer using tested code. Without the
void* you couldn't even have a generic qsort to call. This is an
argument for adding "typeof(x)" to the language.
 
R

Randy Howard

Without the void* you couldn't even have a generic qsort to call. This
is an argument for adding "typeof(x)" to the language.

It would certainly be a whole lot more useful than strcat_s() and friends.
Of course, waiting for either to show up in your shiny new C07-conforming
compiler might take longer than your life expectancy. :-(
 

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

Members online

Forum statistics

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

Latest Threads

Top