473,395 Members | 1,343 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Casting return of malloc

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

Nov 14 '05 #1
35 2624
In article <11**********************@g14g2000cwa.googlegroups .com>,
yt****@gmail.com <yt****@gmail.com> wrote:
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.


It isn't necessary, and it hides errors. Why do the extra typing for
something with a negative benefit?
dave

--
Dave Vandervies dj******@csclub.uwaterloo.ca
Having said that, you tend to be a lot less wrong than most people (which
might be why we take such an unholy delight in trying to find errors in
what you write). --Richard Heathfield in comp.lang.c
Nov 14 '05 #2
yt****@gmail.com <yt****@gmail.com> scribbled the following:
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.


It won't fix anything, but it may make the compiler think problems are
fixed when they really aren't.

Longer explanation:
Without a proper prototype for malloc(), the compiler thinks it returns
int. Thus, when malloc creates a void* value and returns it, the
compiler implicitly converts it to int. The value is *already* broken at
this case, so no amount of casting it to anything will help. However,
if you cast it to a pointer type, the compiler will *think* you know
what you're doing, and omit a warning. Thus you get broken code that
looks like working code.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"We sorcerers don't like to eat our words, so to say."
- Sparrowhawk
Nov 14 '05 #3
"yt****@gmail.com" <yt****@gmail.com> 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.

* If you cast to the wrong type by accident, odd failures can
result.

Some others do disagree, such as P.J. Plauger (see article
<9s*****************@nwrddc01.gnilink.net>).

--
"This is a wonderful answer.
It's off-topic, it's incorrect, and it doesn't answer the question."
--Richard Heathfield
Nov 14 '05 #4
Joona I Palaste wrote:
ytrama wrote:
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.

Longer explanation:
Without a proper prototype for malloc(),
the compiler thinks it returns int.
Thus, when malloc creates a void* value and returns it,
the compiler implicitly converts it to int.
The value is *already* broken at this case,
so no amount of casting it to anything will help.
However, if you cast it to a pointer type,
the compiler will *think* you know what you're doing and omit a warning.
Thus you get broken code that looks like working code.


That's *not* true.
cat f.c void f(void) {
char* p = (char*)malloc(128);
for (size_t j = 0; j < 128; ++j)
p[j] = j;
}
gcc -Wall -std=c99 -pedantic -c f.c f.c: In function `f':
f.c:2: warning: implicit declaration of function `malloc'
f.c:3: error: `size_t' undeclared (first use in this function)
f.c:3: error: (Each undeclared identifier is reported only once
f.c:3: error: for each function it appears in.)
f.c:3: error: parse error before "j"
f.c:3: error: `j' undeclared (first use in this function)
f.c:3: error: parse error before ')' token
f.c: At top level:
f.c:2: warning: unused variable `p'

The compiler gives ample diagnostics
should you fail to #include <stdlib.h>
which defines malloc(size_t) and size_t.

On good reason for casting malloc(int) to the desired type
is so you can compile with a C++ compiler:
cat f.cc #include <stdlib.h>

void f(void) {
char* p = malloc(128);
for (size_t j = 0; j < 128; ++j)
p[j] = j;
}
g++ -Wall -ansi -pedantic -c f.cc

f.cc: In function `void f()':
f.cc:4: error: invalid conversion from `void*' to `char*'
Nov 14 '05 #5
Ben Pfaff wrote:
"yt****@gmail.com" <yt****@gmail.com> 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.

* If you cast to the wrong type by accident, odd failures
can result.

Some others do disagree, such as P.J. Plauger (see article
<9s*****************@nwrddc01.gnilink.net>).


and E. Robert Trollsdale. What a combination! It reminds me of
the first term in the process of summing an arithmetic progression,
i.e. (1 + N) + (2 + N-1) ...

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson

Nov 14 '05 #6
<yt****@gmail.com> wrote in message
news:11**********************@g14g2000cwa.googlegr oups.com...
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.


You've got it backwards. Before writing any cast,
find a defensible reason to do so. There is no
such reason when assigning a 'void*' (which is
the type returned by 'malloc()') value to another
(object) pointer type.

-Mike
Nov 14 '05 #7
E. Robert Tisdale wrote:
Joona I Palaste wrote:
ytrama wrote:
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.

Longer explanation:
Without a proper prototype for malloc(),
the compiler thinks it returns int.
Thus, when malloc creates a void* value and returns it,
the compiler implicitly converts it to int. The value is *already*
broken at this case, so no amount of casting it to anything will help.
However, if you cast it to a pointer type,
the compiler will *think* you know what you're doing and omit a warning.
Thus you get broken code that looks like working code.


That's *not* true.
> cat f.c

void f(void) {
char* p = (char*)malloc(128);
for (size_t j = 0; j < 128; ++j)
p[j] = j;
}
> gcc -Wall -std=c99 -pedantic -c f.c

f.c: In function `f':


<snip>
The compiler gives ample diagnostics
should you fail to #include <stdlib.h>
which defines malloc(size_t) and size_t.
There are more compilers than are dreamed of in your philosophy.

Or to be more explicit, why rely on the fact that *some* compilers will
warn when by doing less typing you can ensure that *all* C compilers
will produce a diagnostic.
On good reason for casting malloc(int) to the desired type
is so you can compile with a C++ compiler:


Not a valid reason (except for whatsisname, sorry, I can't remember it)
who has a commercial reason.

The best way to integrate C code with any other language is to compile
it as C and use whatever mechanism the other language provides for the
integration. If you can point me at any C++ compiler vendor who does not
also provide a C compiler that its code will link against I might
reconsider, but such would be extremely rare.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 14 '05 #8
Ben Pfaff <bl*@cs.stanford.edu> writes:
"yt****@gmail.com" <yt****@gmail.com> 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.


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.)
* If you cast to the wrong type by accident, odd failures can
result.

Some others do disagree, such as P.J. Plauger (see article
<9s*****************@nwrddc01.gnilink.net>).


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

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #9
Keith Thompson <ks***@mib.org> writes:
Ben Pfaff <bl*@cs.stanford.edu> writes:
"yt****@gmail.com" <yt****@gmail.com> 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.


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


Often I give this advice to novices, who in many cases seem to
believe that the proper way to deal with warnings is to disable
them. Experts, of course, know better, but experts are not in
need of advice from me.
* If you cast to the wrong type by accident, odd failures can
result.

Some others do disagree, such as P.J. Plauger (see article
<9s*****************@nwrddc01.gnilink.net>).


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 think you're right. I will rephrase my advice for future
posts. How about this:

In unusual circumstances it may make sense to cast the return
value of malloc(). P. J. Plauger, for example, has good
reasons to want his code to compile as both C and C++,
and C++ requires the cast. However, Plauger's case is rare
indeed. Most programmers should write their code as either C
or C++, not in the intersection of the two.
(I can't find that message-id on Google; are you sure it's
correct?)


I can't be sure, if it's not available now, but I cut-and-paste
it instead of trying to retype it, so I don't know what would
have gone wrong.
--
"A lesson for us all: Even in trivia there are traps."
--Eric Sosman
Nov 14 '05 #10
E. Robert Tisdale wrote:
Joona I Palaste wrote:
ytrama wrote:
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.

Longer explanation:
Without a proper prototype for malloc(),
the compiler thinks it returns int.
Thus, when malloc creates a void* value and returns it,
the compiler implicitly converts it to int. The value is *already*
broken at this case, so no amount of casting it to anything will help.
However, if you cast it to a pointer type,
the compiler will *think* you know what you're doing and omit a warning.
Thus you get broken code that looks like working code.

That's *not* true.
> cat f.c

use of size_t without <stdio.h> or <stdlib.h> requires
#include <stddef.h>

Your example is broken.
void f(void) {
char* p = (char*)malloc(128);
for (size_t j = 0; j < 128; ++j)
p[j] = j;
}
> gcc -Wall -std=c99 -pedantic -c f.c f.c: In function `f':
f.c:2: warning: implicit declaration of function `malloc'
f.c:3: error: `size_t' undeclared (first use in this function)
f.c:3: error: (Each undeclared identifier is reported only once
f.c:3: error: for each function it appears in.)
f.c:3: error: parse error before "j"
f.c:3: error: `j' undeclared (first use in this function)
f.c:3: error: parse error before ')' token
f.c: At top level:
f.c:2: warning: unused variable `p'

The 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. Many people unfortunately ignore warnings.

On 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; C++ compilers cannot compile many
standard conforming C programs as C and C++ are different
languages.
Apart from a select few exceptions, mixing of C and C++
is unnecessary and unnecessarily dangerous. C++ specified
an interface to C for a very good reason.
-Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #11
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

Some others do disagree, such as P.J. Plauger
(see article <9s*****************@nwrddc01.gnilink.net>).


Did you really mean to post an email address here?

Nov 14 '05 #12
E. Robert Tisdale wrote:
Ben Pfaff wrote:
I don't recommend casting the return value of malloc():

Some others do disagree, such as P.J. Plauger
(see article <9s*****************@nwrddc01.gnilink.net>).


Did you really mean to post an email address here?


You probably meant

http://www.stanford.edu/~blp/writing...lloc-cast.html

and

http://groups-beta.google.com/group/...?output=gplain
Nov 14 '05 #13
E. Robert Tisdale wrote:
Ben Pfaff wrote:
Some others do disagree, such as P.J. Plauger
(see article <9s*****************@nwrddc01.gnilink.net>).


Did you really mean to post an email address here?


That's no email address. It's a message ID. To be specific it's the
message id of the following message:

http://groups.google.com/gr*********...ink.net&rnum=1

--
If geiger counter does not click,
the coffee, she is just not thick
Nov 14 '05 #14
Sebastian Hungerecker <se****@web.de> scribbled the following:
E. Robert Tisdale wrote:
Ben Pfaff wrote:
Some others do disagree, such as P.J. Plauger
(see article <9s*****************@nwrddc01.gnilink.net>).
Did you really mean to post an email address here?

That's no email address. It's a message ID. To be specific it's the
message id of the following message: http://groups.google.com/gr*********...ink.net&rnum=1


Frankly, I believe Trollsdale knew that. I don't think anyone would be
stupid enough to think a string of text with something so unreadable
(even including a $ sign, no less) before the "@" sign was an e-mail
address, even though the mere sight of the "@" sign screams "e-mail
address!!!" to 99.999% of the world's literate population.
It's just that Trollsdale is being Trollsdale again. He pretends to be
stupider than he really is, hoping it will annoy people.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ------------- Finland --------\
\-------------------------------------------------------- rules! --------/
"We're women. We've got double standards to live up to."
- Ally McBeal
Nov 14 '05 #15
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.
as C and C++ are different languages.
C++ contains almost all of C.
Apart from a select few exceptions,
mixing of C and C++ is unnecessary and unnecessarily dangerous.
Who said anything about "mixing" C and C++?
When I compile C programs with my C++ compiler, they *are* C++ programs.
C++ specified an interface to C for a very good reason.


C++ does *not* specify an interface to C.
It specifies extern "C" to *help* with linkage.
The C++ compiler must be compatible with the C compiler
which might be accomplished
if, for example, the C++ compiler conforms with
the C Application Binary Interface (ABI)
for the target platform.
Nov 14 '05 #16
Joona I Palaste wrote:
He pretends to be stupider than he really is,


I'm not pretending. ;-)

I'm as stupid as I appear to be.

But I'd like to believe that you are pretending.
Nov 14 '05 #17
"E. Robert Tisdale" wrote:

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.


It generally fails to compile mine.
as C and C++ are different languages.


C++ contains almost all of C.


Not enough. More to the point, too much extra.
Apart from a select few exceptions,
mixing of C and C++ is unnecessary and unnecessarily dangerous.


Who said anything about "mixing" C and C++?
When I compile C programs with my C++ compiler, they *are* C++ programs.


Then please feel free to discuss them in comp.lang.c++
<snip>
Nov 14 '05 #18
In article <cu**********@nntp1.jpl.nasa.gov>,
E. Robert Tisdale <E.**************@jpl.nasa.gov> wrote:
On good reason for casting malloc(int) to the desired type
is so you can compile with a C++ compiler:


And if you do this:

#define BEGIN {
#define END }
#define IF if(
#define THEN )

you can write even worse code that you can compile with a Pascal
compiler too!

(Wait, you've suggested doing this before, haven't you? Forget I said
anything...)
dave

--
Dave Vandervies dj******@csclub.uwaterloo.ca
Would you perchance feel like compiling Java in your C++ compiler? ... from
my understanding of the languages in question you could probably hack up a
program which is valid Java and compiles as C++. --Ian Woods in CLC
Nov 14 '05 #19
In article <cu**********@nntp1.jpl.nasa.gov>, E.**************@jpl.nasa.gov
says...
I'm as stupid as I appear to be.


You are being far too modest.

--
Randy Howard (2reply remove FOOBAR)
"Making it hard to do stupid things often makes it hard
to do smart ones too." -- Andrew Koenig
Nov 14 '05 #20
> Ben Pfaff <bl*@cs.stanford.edu> writes:
"yt****@gmail.com" <yt****@gmail.com> 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
<9s*****************@nwrddc01.gnilink.net>).


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

Nov 14 '05 #21
In article <cu**********@nntp1.jpl.nasa.gov>, E.**************@jpl.nasa.gov
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
Nov 14 '05 #22
Randy Howard <ra*********@FOOverizonBAR.net> writes:
In article <cu**********@nntp1.jpl.nasa.gov>, E.**************@jpl.nasa.gov
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;}
Nov 14 '05 #23
In article <87************@benpfaff.org>,
Ben Pfaff <bl*@cs.stanford.edu> 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 dj******@csclub.uwaterloo.ca
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
Nov 14 '05 #24
dj******@csclub.uwaterloo.ca (Dave Vandervies) writes:
In article <87************@benpfaff.org>,
Ben Pfaff <bl*@cs.stanford.edu> 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
Nov 14 '05 #25
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.
Nov 14 '05 #26
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?

Nov 14 '05 #27
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?
Nov 14 '05 #28
In article <cu**********@nntp1.jpl.nasa.gov>, E.**************@jpl.nasa.gov
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
Nov 14 '05 #29
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

Nov 14 '05 #30
Peter Nilsson wrote:
.... 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.

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #31
CBFalconer wrote:
Peter Nilsson wrote:
... 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 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 */

--
Peter

Nov 14 '05 #32
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
Joona I Palaste wrote:
ytrama wrote:
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
Nov 14 '05 #33
Joona I Palaste <pa*****@cc.helsinki.fi> wrote:
Sebastian Hungerecker <se****@web.de> scribbled the following:
E. Robert Tisdale wrote:
Ben Pfaff wrote:
Some others do disagree, such as P.J. Plauger
(see article <9s*****************@nwrddc01.gnilink.net>).

Did you really mean to post an email address here?
That's no email address. It's a message ID. To be specific it's the
message id of the following message:

http://groups.google.com/gr*********...ink.net&rnum=1


(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
Nov 14 '05 #34
Peter Nilsson wrote:
CBFalconer wrote:
Peter Nilsson wrote:

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

--
"If you want to post a followup via groups.google.com, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #35
In article <42***************@yahoo.com>, cb********@yahoo.com says...
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. :-(

--
Randy Howard (2reply remove FOOBAR)
"Making it hard to do stupid things often makes it hard
to do smart ones too." -- Andrew Koenig
Nov 14 '05 #36

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

Similar topics

231
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...
33
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...
14
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...
41
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...
101
by: Tinkertim | last post by:
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 : ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...
0
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.