Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Common misconceptions about C (C95)

39 views
Skip to first unread message

Ioannis Vranos

unread,
Nov 17, 2009, 10:35:56 PM11/17/09
to
I have created a text available under GNU FDL 3 (Free Documenation License)
or later, regarding "Common misconceptions about C" (C95).


http://www.cpp-software.net/documents/free_documents/c_misconceptions.html


Any constructive comments/error corrections are welcome. :-)

Best regards,


--
Ioannis Vranos

C95 / C++03 Software Developer

http://www.cpp-software.net

Seebs

unread,
Nov 17, 2009, 10:50:07 PM11/17/09
to
On 2009-11-18, Ioannis Vranos <wooj...@huskies.com> wrote:
> Any constructive comments/error corrections are welcome. :-)

You state that "Note: Empty parentheses are not equivalent to void arguments
in C, and should be avoided in function declarations and definitions, other
than main()."

I agree that they should be avoided, but I currently think that in a
function definition, they are "equivalent". (Which does not necessarily
mean that they have exactly the same effects on other code.)

You are incorrect to state that there are no implicit type conversions
for variadic functions. More precise would be to state that the implicit
type conversions are the default promotions (integer types smaller than int
to int, floating point types to double) rather than promotions specific to
the function. In the presence of a prototype, the arguments for which the
variadic function has corresponding declarations in its prototype get the
normal conversions, and it is only the arguments AFTER that which get
the default promotions.

I don't think it's poor coding practice to rely on the fact that '9' - '0' is
exactly 9; it's in the spec, and I think people have pretty much committed
to it.

Your example for the <ctype.h> functions is incorrect. You are passing
plain char to them, but they take unsigned char values. On a machine
with signed char, a character that happens to have a negative representation
will come out wrong. Also, getchar() returns an int, and you should probably
use an int variable to hold its result -- this solves the problem, as getchar
returns things in the range for unsigned char (or EOF, which is negative,
on error).

I'm not sold on the wchar_t material; I think multibyte characters are also
basically supported, but really, neither is completely portable -- at least,
not enough that you can reasonably assume that you can create a program
whose source will work on an arbitrary system and print Greek letters. (Maybe
I'm too pessimistic here.)

The string literal form explicitly supports multibyte characters -- although
that obviously depends on your target environment. But then, so does passing
arbitrary strings in as wchar_t, I suspect.

-s
--
Copyright 2009, all wrongs reversed. Peter Seebach / usenet...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!

Keith Thompson

unread,
Nov 17, 2009, 11:17:50 PM11/17/09
to
Seebs <usenet...@seebs.net> writes:
> On 2009-11-18, Ioannis Vranos <wooj...@huskies.com> wrote:
>> Any constructive comments/error corrections are welcome. :-)
>
> You state that "Note: Empty parentheses are not equivalent to void arguments
> in C, and should be avoided in function declarations and definitions, other
> than main()."
>
> I agree that they should be avoided, but I currently think that in a
> function definition, they are "equivalent". (Which does not necessarily
> mean that they have exactly the same effects on other code.)

Ioannis, in case you missed the recent discussion, the issue is that a
function definition with empty parentheses specifies that the function
has no parameters, but not that it expects no arguments, strange as
that sounds. For example:

void func()
{
/* ... */
}

/* ... */

func(42);

The call's behavior is undefined, but no diagnostic is required, as it
would be if the definition started with "void func(void)".

But why do you say "other than main()"? Surely the main function, if
argc and argv are not used, should be declared as
int main(void) { /* ... */ }
not as
int main() { /* ... */ }

A rule that "(void)" is *always* preferable to "()" in function
declarations and definitions is easier to remember.

The latter is likely to work (and yes, the examples in K&R2 use
empty parentheses), but it's not clear that "int main()" is valid,
whereas "int main(void)" definitely is.

[...]

So far, I'm only responding to Seebs's comments; I'll try to find time
to read the document and give it a more thorough review.

--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"

Eric Sosman

unread,
Nov 17, 2009, 11:34:09 PM11/17/09
to
Ioannis Vranos wrote:
> I have created a text available under GNU FDL 3 (Free Documenation License)
> or later, regarding "Common misconceptions about C" (C95).
>
>
> http://www.cpp-software.net/documents/free_documents/c_misconceptions.html
>
>
> Any constructive comments/error corrections are welcome. :-)

Misconception #3: There seems to be a misconception here,
or at least a confusing statement. The variable arguments to
a variadic functions are subject to "the default argument
promotions," so saying that "implicit type conversions do not
take place" is at best misleading. The first printf() call is
not erroneous, but valid.

Misconception #5: It *is* possible to use printf() "without
including any header file," because printf() is a Standard
library function that can be declared free-hand, without use
of a Standard header (unlike fopen(), say). Of course, it's
a dumb idea to write such a declaration -- but maintaining
that it's impossible isn't right.

Misconception #11: Might be positioned near #1 for greater
effect and better continuity of exposition.

Misconception #13: Might be combined with #12 for brevity's
sake. "Brevity is the soul of wit," so if you can shrink
something by half that makes you a ...

General observation: There are quite a few misconceptions
about C that you have not touched upon, like "An int has 32
bits" and "Pointers are faster than array indices" and "The
size of a struct is the sum of the sizes of its elements."
But rather than try to fill a long list, why not just refer
people to the FAQ? Not meaning to be disrespectful, but what
does this list do that the FAQ hasn't already done?

--
Eric Sosman
eso...@ieee-dot-org.invalid

Ioannis Vranos

unread,
Nov 17, 2009, 11:51:04 PM11/17/09
to
Seebs wrote:
>
> I agree that they should be avoided, but I currently think that in a
> function definition, they are "equivalent". (Which does not necessarily
> mean that they have exactly the same effects on other code.)


I think that in function definitions are not "equivalent", and it is a bad
style practice. For example consider the code:


void f() { }

int main(void)
{
/* Obviously the user expects different functionality than what f()
* provides.
*/
f(4);


return 0;
}

The good style would catch the mistake:


void f(void) { }

int main(void)
{
/* It catches the mistake. */
f(4);


return 0;
}


Another example:


/* Bad style, no diagnostic. */

void f() { }

int main(void)
{
void (*p)(int)= f;


p(4);


return 0;
}

/* Good style, we get a diagnostic. */

void f(void) { }

int main(void)
{
void (*p)(int)= f;


p(4);


return 0;
}


> You are incorrect to state that there are no implicit type conversions
> for variadic functions. More precise would be to state that the implicit
> type conversions are the default promotions (integer types smaller than
> int to int, floating point types to double) rather than promotions
> specific to
> the function. In the presence of a prototype, the arguments for which the
> variadic function has corresponding declarations in its prototype get the
> normal conversions, and it is only the arguments AFTER that which get
> the default promotions.


You are right, I will have to rephrase that.


>
> I don't think it's poor coding practice to rely on the fact that '9' - '0'
> is exactly 9; it's in the spec, and I think people have pretty much
> committed to it.


I think it is a poor practice usually.


Under specific situations it can be helpful, like goto can be helpful too.

>
> Your example for the <ctype.h> functions is incorrect.

The code is:


#include <stdio.h>
#include <ctype.h>


int main(void)
{
char c= getchar();

if( islower(c) )
printf("\nThe character is lower case.\n");

else
if( isupper(c) )
printf("\nThe character is upper case.\n");

else
if( isdigit(c) )
printf("\nThe character is a decimal digit.\n");

return 0;
}


> You are passing
> plain char to them, but they take unsigned char values.


Actually they are taking an int, with valid value ranges either the value
EOF, or a value representable as unsigned char.

Since "char c" gets its value from getchar() (probably it would be more
elegant if c was an int, however I do not check for EOF in this code
snippet), there is no way to get undefined behaviour in the above code.

Also, as far as I know, getchar() returns only character values of the basic
character set (value ranges in [0, 127]), and EOF, and not other character
values of the extended character set.


However I will change it to int.

> . On a machine
> with signed char, a character that happens to have a negative
> representation
> will come out wrong.


With "signed char", I suppose you meant "plain char implemented as signed
integer type".


As far as I know, C90/C95 does not allow a character to have a negative
representation.


> Also, getchar() returns an int, and you should
> probably use an int variable to hold its result -- this solves the
> problem, as getchar returns things in the range for unsigned char (or EOF,
> which is negative, on error).
>
>
> I'm not sold on the wchar_t material; I think multibyte characters are
> also basically supported, but really, neither is completely portable -- at
> least, not enough that you can reasonably assume that you can create a
> program
> whose source will work on an arbitrary system and print Greek letters.
> (Maybe I'm too pessimistic here.)


Yes, because actually a system may not have Greek or some other non-latin
characters language support installed or ability to provide.

Keith Thompson

unread,
Nov 18, 2009, 12:16:06 AM11/18/09
to
Ioannis Vranos <wooj...@huskies.com> writes:
> Seebs wrote:
[...]

A brief comment: You have a lot more blank lines than you need
in your code samples.

[...]

>> Your example for the <ctype.h> functions is incorrect.
>
> The code is:
>
> #include <stdio.h>
> #include <ctype.h>
>
>
> int main(void)
> {
> char c= getchar();
>
> if( islower(c) )
> printf("\nThe character is lower case.\n");
>
> else
> if( isupper(c) )
> printf("\nThe character is upper case.\n");
>
> else
> if( isdigit(c) )
> printf("\nThe character is a decimal digit.\n");
>
> return 0;
> }

A side comment: the usual style is to put "else if" on one line:

if( islower(c) )
...
else if( isupper(c) )
...
else if( isdigit(c) )
...

>> You are passing
>> plain char to them, but they take unsigned char values.
>
> Actually they are taking an int, with valid value ranges either the value
> EOF, or a value representable as unsigned char.

Right.

> Since "char c" gets its value from getchar() (probably it would be more
> elegant if c was an int, however I do not check for EOF in this code
> snippet), there is no way to get undefined behaviour in the above code.

Yes, there is. getchar() can easily return a value that exceeds
CHAR_MAX (if plain char is signed).

> Also, as far as I know, getchar() returns only character values of the basic
> character set (value ranges in [0, 127]), and EOF, and not other character
> values of the extended character set.

Incorrect. A concrete example: if plain char is signed, 8 bits, and
the system's character set (in the current locale) is ISO-8859-1, if
the user enters 'e' with an acute accent ('é'), getchar() will return
the value 233, which when stored in a plain char will be converted to
-23. islower(-23) invokes undefined behavior.

[...]

> As far as I know, C90/C95 does not allow a character to have a negative
> representation.

It does. C90 6.1.2.5 says:

An object declared as type char is large enough to store any
member of the basic execution character set. If a member of the
required source character set enumerated in 5.2.1 is stored
in a char object, its value is guaranteed to be positive. If
other quantities are stored in a char object, the behavior is
implementation-defined; the values are treated as either signed
or nonnegative integers.

Similarly, C99 (actually N1256) 6.2.5p4 says:

An object declared as type char is large enough to store any
member of the basic execution character set. If a member of
the basic execution character set is stored in a char object,
its value is guaranteed to be nonnegative. If any other
character is stored in a char object, the resulting value is
implementation-defined but shall be within the range of values
that can be represented in that type.

Members of the basic execution character set must be non-negative, but
members of the extended character set may be negative.

[...]

Michael Tsang

unread,
Nov 18, 2009, 12:23:02 AM11/18/09
to
Ioannis Vranos wrote:

> I have created a text available under GNU FDL 3 (Free Documenation
> License) or later, regarding "Common misconceptions about C" (C95).
>
>
> http://www.cpp-software.net/documents/free_documents/c_misconceptions.html
>
>
> Any constructive comments/error corrections are welcome. :-)
>
>
>
> Best regards,
>
>

Why do you still write a document about an outdated C standard. The current
version is C99.

Seebs

unread,
Nov 18, 2009, 12:27:17 AM11/18/09
to
On 2009-11-18, Ioannis Vranos <wooj...@huskies.com> wrote:
> I think that in function definitions are not "equivalent", and it is a bad
> style practice. For example consider the code:

It may be a bad style practice. I'm well aware of the way in which they can
deny you expected diagnostics.

However, there is definitely a formal equivalence, in that both are described,
when used in a function definition, as specifying that the function takes no
arguments.

>> I don't think it's poor coding practice to rely on the fact that '9' - '0'
>> is exactly 9; it's in the spec, and I think people have pretty much
>> committed to it.

> I think it is a poor practice usually.

Why?

It's guaranteed by the standard. It's worked everywhere always.

> #include <stdio.h>
> #include <ctype.h>
>
> int main(void)
> {
> char c= getchar();
>
> if( islower(c) )
> printf("\nThe character is lower case.\n");
>
> else
> if( isupper(c) )
> printf("\nThe character is upper case.\n");
>
> else
> if( isdigit(c) )
> printf("\nThe character is a decimal digit.\n");
>
> return 0;
> }
>
>
>> You are passing
>> plain char to them, but they take unsigned char values.
>
> Actually they are taking an int, with valid value ranges either the value
> EOF, or a value representable as unsigned char.

Right. But 'char c = getchar()' is not guaranteed to yield a value which
can be passed to them.

> Since "char c" gets its value from getchar() (probably it would be more
> elegant if c was an int, however I do not check for EOF in this code
> snippet), there is no way to get undefined behaviour in the above code.

Yes, there is.

> Also, as far as I know, getchar() returns only character values of the basic
> character set (value ranges in [0, 127]), and EOF, and not other character
> values of the extended character set.

Wrong.

getchar() returns arbitrary characters from the execution character set,
having first converted them to the range of unsigned char.

On a machine where plain char is signed and 8 bits, it is certainly possible
for getchar() to return 200. Converted to char, this yields a negative
value which is not a valid argument for isalpha(), etc.

> With "signed char", I suppose you meant "plain char implemented as signed
> integer type".

Yes.

> As far as I know, C90/C95 does not allow a character to have a negative
> representation.

You are incorrect. Plain char must have the same representation as either
signed char or unsigned char, but it is allowed to be either. It can have
a negative representation in plain char.

Michael Tsang

unread,
Nov 18, 2009, 12:29:17 AM11/18/09
to
Ioannis Vranos wrote:

> I have created a text available under GNU FDL 3 (Free Documenation
> License) or later, regarding "Common misconceptions about C" (C95).
>
>
> http://www.cpp-software.net/documents/free_documents/c_misconceptions.html
>
>
> Any constructive comments/error corrections are welcome. :-)
>
>
>
> Best regards,
>
>

10. Use of malloc without casting is considered a poor practice (it is an
error in C++). Cast it to suitable type instead.

Keith Thompson

unread,
Nov 18, 2009, 12:39:30 AM11/18/09
to

No, casting the result of malloc is considered poor practice in C.
This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.

Gordon Burditt

unread,
Nov 18, 2009, 12:54:47 AM11/18/09
to
>Also, as far as I know, getchar() returns only character values of the basic
>character set (value ranges in [0, 127]), and EOF, and not other character
>values of the extended character set.

This is not true. getchar() may return any character of the runtime
character set. The C standard defines the basic character set as
being the uppercase alphabetic, lowercase alphabetic, digits, space,
a few specific control characters, and a list of specific punctuation
marks. This does *NOT* include all the ASCII characters in the range
[0,127], nor all of the printable ASCII characters in the range
[33, 126].

Any character that is part of the runtime character set (say, ISO
Latin-1) but not part of the basic character set may have a negative
representation. getchar() will return the code for an accented
letter, and if you assign that value to a (plain, presumably signed)
char, it will have a negative value.


>As far as I know, C90/C95 does not allow a character to have a negative
>representation.

Characters in the runtime character set other than those in the basic
character set may have a negative representation.

spinoza1111

unread,
Nov 18, 2009, 12:57:38 AM11/18/09
to
On Nov 18, 11:35 am, Ioannis Vranos <woojn...@huskies.com> wrote:
> I have created a text available under GNU FDL 3 (Free Documenation License)
> or later, regarding "Common misconceptions about C" (C95).
>
> http://www.cpp-software.net/documents/free_documents/c_misconceptions...

>
> Any constructive comments/error corrections are welcome.   :-)
>
> Best regards,
>
> --
> Ioannis Vranos
>
> C95 / C++03 Software Developer
>
> http://www.cpp-software.net

I gave you five stars because:

(1) The list seems useful to me despite the fact that it may not be
100% correct: 100% correctness is not possible in C, since C is an out-
dated language and a series of technical errors

(2) You did not attack Herb Schildt but wrote like a MAN and a
PROFESSIONAL about ideas and concepts, TEACHING other people to the
best of your ability

(3) You use English well and when you misspell you misspell in an
Attic (Greek) way that I like, as in invokation instead of invocation

Please stick around and don't mind the behavior of Seebach et al. They
think this ng is their personal fiefdom and they tend to transform
technical issues into campaigns of personal destruction owing to their
insecurity.

spinoza1111

unread,
Nov 18, 2009, 1:10:35 AM11/18/09
to
On Nov 18, 12:34 pm, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
> Ioannis Vranos wrote:
> > I have created a text available under GNU FDL 3 (Free Documenation License)
> > or later, regarding "Common misconceptions about C" (C95).
>
> >http://www.cpp-software.net/documents/free_documents/c_misconceptions...

>
> > Any constructive comments/error corrections are welcome.   :-)
>
>      Misconception #3: There seems to be a misconception here,
> or at least a confusing statement.  The variable arguments to
> a variadic functions are subject to "the default argument
> promotions," so saying that "implicit type conversions do not
> take place" is at best misleading.  The first printf() call is
> not erroneous, but valid.
>
>      Misconception #5: It *is* possible to use printf() "without
> including any header file," because printf() is a Standard
> library function that can be declared free-hand, without use
> of a Standard header (unlike fopen(), say).  Of course, it's
> a dumb idea to write such a declaration -- but maintaining
> that it's impossible isn't right.
>
>      Misconception #11: Might be positioned near #1 for greater
> effect and better continuity of exposition.
>
>      Misconception #13: Might be combined with #12 for brevity's
> sake.  "Brevity is the soul of wit," so if you can shrink
> something by half that makes you a ...
>
>      General observation: There are quite a few misconceptions
> about C that you have not touched upon, like "An int has 32
> bits" and "Pointers are faster than array indices" and "The

Why is it not the case that pointers are faster than array indices?

Are they not-faster some of the time, or are they not-faster all of
the time?

In a normal language you need to convert the index at compile or at
run time to the pointer by multiplying times the size of array
elements and adding the base address.

If there are things about C that make good programming practice bad,
and destroy knowledge, then C is the problem, isn't it?

And today, an int has 32 bits because today, 64 bits are in common use
yet common parlance recognizes the fact that 64 bits provides far more
precision than will ever be needed by most applications, and it is
unlikely that we shall need more. Therefore it makes sense in common
CS parlance to refer to the 64 bit integer as long, which entails
referring to the 32 bit integer as int. It is to be a troll from the
dark ages to want to call a 16 bit integer int, a 32 bit integer long,
and a 64 bit integer long long, or at a minimum it is to want to live
in the past.

Many creepy little C programmers creep into night skewl and find the
professor using a CS language which generalizes over language in this
way and decide that the prof doesn't know what he's talking about, and
this seems to be the case here.

> size of a struct is the sum of the sizes of its elements."

Would it were true. But many platforms pad. This is why in modern
languages it is MEANINGLESS to speak of the size of a struct. A struct
is a lightweight class in C sharp and it MAKES NO SENSE to talk about
its size, nor is it necessary, because in an array of structs (a
permitted construct in C Sharp) we do not want to know the address of
any member. It's "undefined".

> But rather than try to fill a long list, why not just refer
> people to the FAQ?  Not meaning to be disrespectful, but what
> does this list do that the FAQ hasn't already done?
>
> --
> Eric Sosman

> esos...@ieee-dot-org.invalid

Seebs

unread,
Nov 18, 2009, 1:43:24 AM11/18/09
to
On 2009-11-18, Michael Tsang <mik...@gmail.com> wrote:
> 10. Use of malloc without casting is considered a poor practice

This is false.

> (it is an error in C++).

This is true, but irrelevant.

Use of malloc with a cast regularly hides errors that should have been
caught by the compiler. Use of malloc without a cast is portable, reliable,
and correct.

C++ intentionally broke this behavior because, in C++, you should be
using operator new anyway.

Richard Heathfield

unread,
Nov 18, 2009, 4:07:10 AM11/18/09
to
In <9ac56d86-87a8-418c...@13g2000prl.googlegroups.com>,
spinoza1111 wrote:

> On Nov 18, 12:34 pm, Eric Sosman <esos...@ieee-dot-org.invalid>
> wrote:

<snip>


>>
>> General observation: There are quite a few misconceptions
>> about C that you have not touched upon, like "An int has 32
>> bits" and "Pointers are faster than array indices" and "The
>
> Why is it not the case that pointers are faster than array indices?

C doesn't make any specific performance guarantees about *anything*;
and rightly so, since performance is characteristic of
implementations, not the language itself. What it does say is that
arr[ind] and *(arr + ind) are equivalent, so there's no particular
difference to be deduced. The misconception stems from early days
when, on some implementations, there was a real speed difference
between the two forms. Nowadays, optimising compilers are pretty good
at this kind of thing.

> Are they not-faster some of the time, or are they not-faster all of
> the time?

No specific guarantees - if it matters (which normally it doesn't),
measure it, and bear in mind that the measurement will only be good
for the specific circumstances under which it was taken - if you
change the optimisation level, or the compiler, or the platform, or
whatever, the results may and probably will vary.

<nonsense snipped>

> And today, an int has 32 bits

Not on all platforms. On some it's 48. On some it's 64.

<nonsense snipped>

>> size of a struct is the sum of the sizes of its elements."
>
> Would it were true. But many platforms pad.

Sure.

> This is why in modern
> languages it is MEANINGLESS to speak of the size of a struct.

On the contrary, it's a very useful and much-used idea.

<snip>

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within

Richard Heathfield

unread,
Nov 18, 2009, 4:10:05 AM11/18/09
to
In <he00bg$sjn$1...@news.eternal-september.org>, Michael Tsang wrote:

<snip>



> Why do you still write a document about an outdated C standard.

Presumably because, outdated or not, it remains the de facto standard.

> The current version is C99.

...which remains unimplemented by Microsoft, Borland, and gcc (the
three most common implementations in use on the most common desktop
platform) - although gcc does come pretty close.

Pietro Cerutti

unread,
Nov 18, 2009, 5:01:11 AM11/18/09
to
On Tue, 17 Nov 2009 21:57:38 -0800, spinoza1111 wrote:

[snip]

> I gave you five stars because:

[snip]

> (2) You did not attack Herb Schildt but wrote like a MAN and a
> PROFESSIONAL about ideas and concepts, TEACHING other people to the best
> of your ability

[snip]

Great evaluation criteria, indeed... Thanks for the good laugh!

Richard Tobin

unread,
Nov 18, 2009, 5:38:49 AM11/18/09
to
In article <9ac56d86-87a8-418c...@13g2000prl.googlegroups.com>,
spinoza1111 <spino...@yahoo.com> wrote:

>Why is it not the case that pointers are faster than array indices?
>
>Are they not-faster some of the time, or are they not-faster all of
>the time?
>
>In a normal language you need to convert the index at compile or at
>run time to the pointer by multiplying times the size of array
>elements and adding the base address.

It's certainly true that in a naively-compiled program, there may be a
cost to converting an array element expression to an address. This is
not always so: if the array elements have size 1 there is no
multiplication, and it's possible that the processor may have
addressing modes where the addition has no overhead.

It's also possible that better optimisation can be done in the case
of an array reference. Consider these alternatives:

int a[10], b[10], x;
int *pointer;
pointer = compute_pointer(a, b, ...args...);
a[1] = 25;
*pointer = 42;
x = a[1];

and

int a[10], b[10], x;
int index;
index = compute_index(a, b, ...args...);
a[1] = 25;
b[index] = 42;
x = a[1];

In the first case the compiler cannot tell whether a[1] will still be
25 when it is assigned to x. It might be 42 if computer_pointer
returned a pointer into a.

In the second case, the compiler can see that it's b that is modified,
and there's no possibility of a[1] having been changed. Using the
less powerful array indexing instead of a pointer also helps the
human reader see what is happening.

So pointers may be slower or faster than, or the same speed as, array
references.

-- Richard
--
Please remember to mention me / in tapes you leave behind.

Richard Tobin

unread,
Nov 18, 2009, 5:41:00 AM11/18/09
to
In article <slrnhg763j.76k...@guild.seebs.net>,
Seebs <usenet...@seebs.net> wrote:

>Use of malloc with a cast regularly hides errors that should have been
>caught by the compiler.

Much less of a problem now that compilers generally warn about
undeclared functions.

Richard Heathfield

unread,
Nov 18, 2009, 5:43:20 AM11/18/09
to
In <he0ivs$hfr$2...@pc-news.cogsci.ed.ac.uk>, Richard Tobin wrote:

> In article <slrnhg763j.76k...@guild.seebs.net>,
> Seebs <usenet...@seebs.net> wrote:
>
>>Use of malloc with a cast regularly hides errors that should have
>>been caught by the compiler.
>
> Much less of a problem now that compilers generally warn about
> undeclared functions.

I think the worst thing (for me) about malloc casting is that it looks
downright ugly!

jacob navia

unread,
Nov 18, 2009, 5:44:49 AM11/18/09
to
Richard Tobin a �crit :

> In article <slrnhg763j.76k...@guild.seebs.net>,
> Seebs <usenet...@seebs.net> wrote:
>
>> Use of malloc with a cast regularly hides errors that should have been
>> caught by the compiler.
>
> Much less of a problem now that compilers generally warn about
> undeclared functions.
>
> -- Richard

C++ NEEDS the cast... If you ever want to compile your code in C++ mode
it is better to leave the cast there.

Richard Heathfield

unread,
Nov 18, 2009, 6:02:27 AM11/18/09
to

Better still, remove both the cast and the call, and replace it with
new or new[].

bartc

unread,
Nov 18, 2009, 6:51:40 AM11/18/09
to

"Ioannis Vranos" <wooj...@huskies.com> wrote in message
news:hdvq2t$1t7p$1...@ulysses.noc.ntua.gr...

>I have created a text available under GNU FDL 3 (Free Documenation License)
> or later, regarding "Common misconceptions about C" (C95).
>
>
> http://www.cpp-software.net/documents/free_documents/c_misconceptions.html
>
>
> Any constructive comments/error corrections are welcome. :-)

Why is it double- (and sometimes triple- and quadruple-) spaced? That makes
it hard to follow.

The license section (about 60% of the bulk of the document) is a
distraction. Why not just make it a link.

--
Bartc


Walter Banks

unread,
Nov 18, 2009, 7:08:46 AM11/18/09
to

spinoza1111 wrote:

> > General observation: There are quite a few misconceptions
> > about C that you have not touched upon, like "An int has 32
> > bits" and "Pointers are faster than array indices" and "The
>
> Why is it not the case that pointers are faster than array indices?
>
> Are they not-faster some of the time, or are they not-faster all of
> the time?

Start with some basic metrics. Count cycles and generated code.

a) Take the half dozen or so cases and hand code them up as
micro operations and

b) then separate all those micro operations that can be done at
compile time and those that must be done at run time

c) Map the micro operations on the instruction set you are using
and count cycles and bytes.

The most significant differences will be the base address of an
array is generally a constant that can often be optimized out
with instruction selection or compile time math.

Constant index references are generally a big win for arrays
in most execution environments

You really probably should have finished your book. Code
generation and optimization are about 90% of creating a
compiler. This stuff is pretty fundamental to that process.


Regards,

--
Walter Banks
Byte Craft Limited
http://www.bytecraft.com

Kenny McCormack

unread,
Nov 18, 2009, 7:15:17 AM11/18/09
to
In article <lnocn0z...@nuthaus.mib.org>,
Keith Thompson <ks...@mib.org> wrote:
...

>> 10. Use of malloc without casting is considered a poor practice (it is an
>> error in C++). Cast it to suitable type instead.
>
>No, casting the result of malloc is considered poor practice in C.
>This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.

You are both right, of course. The key question being:"considered" by
whom?

BTW, I just heard someone call out "Bingo!".

P.S. The Yankees are considered one of the best teams in baseball.
No. The Phillies are considered one of the best teams in baseball.

See the point?

Tom St Denis

unread,
Nov 18, 2009, 8:40:01 AM11/18/09
to
On Nov 18, 7:15 am, gaze...@shell.xmission.com (Kenny McCormack)
wrote:
> In article <lnocn0z90t....@nuthaus.mib.org>,

> Keith Thompson  <ks...@mib.org> wrote:
> ...
>
> >> 10. Use of malloc without casting is considered a poor practice (it is an
> >> error in C++). Cast it to suitable type instead.
>
> >No, casting the result of malloc is considered poor practice in C.
> >This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.
>
> You are both right, of course.  The key question being:"considered" by
> whom?
>

By people who know the language? By default the function will be
assumed to return an int and the parameter type is not known, so you
could do something like

unsigned long long a = 16;
void *p = malloc(a);

And it wouldn't know to convert 'a' to size_t first or that the return
value is a pointer. Now imagine you're on a platform where sizeof
(int) = 2 and sizeof(void *) = 4 or long long > size_t (entirely
possible). Admittedly, that's all a bit contrived but it's possible.

In short, it's bad form to call functions without a prototype.

Tom

Kenny McCormack

unread,
Nov 18, 2009, 9:07:50 AM11/18/09
to
In article <ac0acf59-374c-4f2c...@e20g2000vbb.googlegroups.com>,

Tom St Denis <t...@iahu.ca> wrote:
>On Nov 18, 7:15�am, gaze...@shell.xmission.com (Kenny McCormack)
>wrote:
>> In article <lnocn0z90t....@nuthaus.mib.org>,
>> Keith Thompson �<ks...@mib.org> wrote:
>> ...
>>
>> >> 10. Use of malloc without casting is considered a poor practice (it is an
>> >> error in C++). Cast it to suitable type instead.
>>
>> >No, casting the result of malloc is considered poor practice in C.
>> >This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.
>>
>> You are both right, of course. �The key question being:"considered" by
>> whom?
>>
>
>By people who know the language? By default the function will be
>assumed to return an int and the parameter type is not known, so you
>could do something like

(The usual CLC arguments - seen many, many times over the years - snipped)

I understand these standard CLC arguments - I also understand the other
side of it. The point is that the "not casting the return value of
malloc()" thing is clearly a shibboleth. That is, a thing by which the
in-crowd recognizes each other, and thus a thing you need to profess to
believe in order to be accepted in the in-crowd.

Richard

unread,
Nov 18, 2009, 9:15:09 AM11/18/09
to

*chuckle*

I am sure Kenny will be very grateful for you explaining this. It has
only been done 10 times a day here for the past 20 years ....


--
"Avoid hyperbole at all costs, its the most destructive argument on
the planet" - Mark McIntyre in comp.lang.c

Richard Tobin

unread,
Nov 18, 2009, 9:29:36 AM11/18/09
to
In article <he0j5r$ai9$1...@aioe.org>, jacob navia <j...@nospam.org> wrote:

>C++ NEEDS the cast... If you ever want to compile your code in C++ mode
>it is better to leave the cast there.

I doubt I will ever want to. I usually try to make my header files
includable in C++, but the executable C code whould just be compiled
as C.

Ioannis Vranos

unread,
Nov 18, 2009, 10:17:56 AM11/18/09
to
jacob navia wrote:


If you want to use C code with C++ code, there is

extern "C".


Otherwise, converting C code to C++ will be messy.


Also, why convert C code to C++? It will be tiresome. There are subtle
differences, like sizeof('a') being different in C and C++, etc..

Lowell Gilbert

unread,
Nov 18, 2009, 10:20:27 AM11/18/09
to
Seebs <usenet...@seebs.net> writes:

> On 2009-11-18, Michael Tsang <mik...@gmail.com> wrote:
>> 10. Use of malloc without casting is considered a poor practice
>
> This is false.

Precisely. That's why it belongs on a list of misconceptions.

--
Lowell Gilbert, embedded/networking software engineer
http://be-well.ilk.org/~lowell/

gwowen

unread,
Nov 18, 2009, 10:23:40 AM11/18/09
to
On Nov 18, 1:40 pm, Tom St Denis <t...@iahu.ca> wrote:

> In short, it's bad form to call functions without a prototype.

So if I use a C99-mode compiler (or -Wmissing-prototypes or
equivalent), the major (sole?) reason for not casting vanishes, right?

Kenny McCormack

unread,
Nov 18, 2009, 10:29:17 AM11/18/09
to
In article <4431fa9c-e8a0-4dcc...@m38g2000yqd.googlegroups.com>,

You are not allowed to discuss C99 in CLC...

Seriously, the "not casting the return value of malloc()" shibboleth
arose mainly out of C89 considerations (the only version approved by
alpha male Dicky H).

Keith Thompson

unread,
Nov 18, 2009, 10:57:16 AM11/18/09
to
Lowell Gilbert <lgus...@be-well.ilk.org> writes:
> Seebs <usenet...@seebs.net> writes:
>> On 2009-11-18, Michael Tsang <mik...@gmail.com> wrote:
>>> 10. Use of malloc without casting is considered a poor practice
>>
>> This is false.
>
> Precisely. That's why it belongs on a list of misconceptions.

Michael Tsang was claiming that the use of malloc without a cast *is*
considered poor practice. Seebs was disagreeing with him (as did I).

Ioannis's web page itself says:

| Misconception 10: Invokations of malloc(), calloc(), and realloc(),
| need casting.
...
| Clarification: Casting is not needed
...

Richard Heathfield

unread,
Nov 18, 2009, 11:10:58 AM11/18/09
to
In <lnk4xnz...@nuthaus.mib.org>, Keith Thompson wrote:

<snip>



> Ioannis's web page itself says:
>
> | Misconception 10: Invokations of malloc(), calloc(), and
> | realloc(), need casting.
> ...
> | Clarification: Casting is not needed

It's astonishing how often this comes up, and how vehemently the
practice is defended. I guess some people just love to type.

spinoza1111

unread,
Nov 18, 2009, 11:09:26 AM11/18/09
to
On Nov 18, 11:29 pm, gaze...@shell.xmission.com (Kenny McCormack)
wrote:
> In article <4431fa9c-e8a0-4dcc-8afd-77ff4fcd6...@m38g2000yqd.googlegroups.com>,

Sounds to me idiotic not to cast. Strong typing better than weak
typing. But the cool, studly kids don't cast. I cast because I'm good
at C and I don't even use it much (which is a sign of a programmer
who's good at C, paradoxically enough).

Richard Heathfield

unread,
Nov 18, 2009, 11:19:49 AM11/18/09
to
In
<d8708124-3045-489b...@f20g2000prn.googlegroups.com>,
spinoza1111 wrote:

<snip>



> Sounds to me idiotic not to cast.

It would.

Keith Thompson

unread,
Nov 18, 2009, 11:21:45 AM11/18/09
to

No.

First of all, C99 removed implicit int, but it still doesn't require
prototypes. That's probably not relevant in this case, since you
still need a visible declaration that specifies the return type.

The real reason not to cast the result of malloc is that *the cast
has no benefit* (except in the rare case where you want to compile
the same code as C and as C++).

I can write:

ptr = malloc(count * sizeof *ptr);

The code is perfectly clear to anyone who knows the language well
enough, and it works. Adding a cast, in the best case, simply adds
information that the compiler already knows. Why bother?

Would you use a cast for this?

float x = (float)sqrt(2.0);

I wouldn't, because it's unnecessary.

Richard Tobin

unread,
Nov 18, 2009, 11:42:53 AM11/18/09
to
In article <d8708124-3045-489b...@f20g2000prn.googlegroups.com>,
spinoza1111 <spino...@yahoo.com> wrote:

>Sounds to me idiotic not to cast. Strong typing better than weak
>typing.

Casting is a way to defeat strong typing.

int a;
char *p;
...
p = a;

This is an error requiring a diagnostic.

int a;
char *p;
...
p = (char *)a;

This is not. The cast tells the compiler *not* to apply its usual
strong typing, but to convert the value to a character pointer
regardless.

Richard Tobin

unread,
Nov 18, 2009, 11:47:07 AM11/18/09
to
In article <he1374$2u49$1...@ulysses.noc.ntua.gr>,
Ioannis Vranos <wooj...@huskies.com> wrote:

>If you want to use C code with C++ code, there is
>
>extern "C".
>
>Otherwise, converting C code to C++ will be messy.
>
>Also, why convert C code to C++? It will be tiresome. There are subtle
>differences, like sizeof('a') being different in C and C++, etc..

If I understand correctly, 'extern "C"' is not for converting arbitrary
C code to C++, but merely to tell the C++ compiler that the contained
declarations are for C functions. Interfacing C++ to C functions is
quite a different matter from compiling executable C code as C++.

Lowell Gilbert

unread,
Nov 18, 2009, 11:43:06 AM11/18/09
to
Keith Thompson <ks...@mib.org> writes:

> Lowell Gilbert <lgus...@be-well.ilk.org> writes:
>> Seebs <usenet...@seebs.net> writes:
>>> On 2009-11-18, Michael Tsang <mik...@gmail.com> wrote:
>>>> 10. Use of malloc without casting is considered a poor practice
>>>
>>> This is false.
>>
>> Precisely. That's why it belongs on a list of misconceptions.
>
> Michael Tsang was claiming that the use of malloc without a cast *is*
> considered poor practice. Seebs was disagreeing with him (as did I).

I was only disagreeing with your reading, not your point.
Your reading does seem more likely to me now.

Ioannis Vranos

unread,
Nov 18, 2009, 11:52:53 AM11/18/09
to
bartc wrote:
>
>
> Why is it double- (and sometimes triple- and quadruple-) spaced? That
> makes it hard to follow.


The page looks OK in my laptop (1920x1080 resolution). :-)


>
> The license section (about 60% of the bulk of the document) is a
> distraction. Why not just make it a link.


The license must be included in the document to be in effect.

Ioannis Vranos

unread,
Nov 18, 2009, 11:59:47 AM11/18/09
to
Ioannis Vranos wrote:
>
> I have created a text available under GNU FDL 3 (Free Documenation
> License) or later, regarding "Common misconceptions about C" (C95).
>
>
> http://www.cpp-software.net/documents/free_documents/c_misconceptions.html
>
>
> Any constructive comments/error corrections are welcome. :-)


I have uploaded a corrected version of the page.


Any constructive comments/error corrections are welcome. :-)

http://www.cpp-software.net/documents/free_documents/c_misconceptions.html

Richard Heathfield

unread,
Nov 18, 2009, 12:13:08 PM11/18/09
to
In <he18eb$o6i$2...@pc-news.cogsci.ed.ac.uk>, Richard Tobin wrote:

<snip>



> If I understand correctly, 'extern "C"' is not for converting
> arbitrary C code to C++, but merely to tell the C++ compiler that
> the contained declarations are for C functions.

Right, and you use extern "C" for that. And then you *link* the
C-compiled object files to the C++-compiled object files.

Ioannis Vranos

unread,
Nov 18, 2009, 12:11:07 PM11/18/09
to
Michael Tsang wrote:
>
> 10. Use of malloc without casting is considered a poor practice (it is an
> error in C++). Cast it to suitable type instead.


C and C++ are different languages.

Nobody

unread,
Nov 18, 2009, 12:13:52 PM11/18/09
to
On Tue, 17 Nov 2009 21:39:30 -0800, Keith Thompson wrote:

>> 10. Use of malloc without casting is considered a poor practice (it is an
>> error in C++). Cast it to suitable type instead.
>

> No, casting the result of malloc is considered poor practice in C.
> This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.

Considered by whom?

I've heard reasonable arguments both for and against. OTOH, I've never
seen evidence (e.g. a survey) that either approach could be considered a
consensus viewpoint.

Richard

unread,
Nov 18, 2009, 12:19:51 PM11/18/09
to
Ioannis Vranos <wooj...@huskies.com> writes:

> Michael Tsang wrote:
>>
>> 10. Use of malloc without casting is considered a poor practice (it is an
>> error in C++). Cast it to suitable type instead.
>
> C and C++ are different languages.

And you posted that why?

Ioannis Vranos

unread,
Nov 18, 2009, 12:21:52 PM11/18/09
to
Nobody wrote:


Since the casting is not needed, using it is a bad style. At least, it shows
that there is luck of C knowledge.

Ioannis Vranos

unread,
Nov 18, 2009, 12:23:48 PM11/18/09
to
Ioannis Vranos wrote:
>
> Since the casting is not needed, using it is a bad style. At least, it
shows that there is lack of C knowledge.

Nobody

unread,
Nov 18, 2009, 12:24:45 PM11/18/09
to
On Wed, 18 Nov 2009 05:40:01 -0800, Tom St Denis wrote:

> In short, it's bad form to call functions without a prototype.

Which is why compilers will typically warn you if you do so.

You don't need to rely upon an "implicit conversion" warning when a more
specific warning is available.

If you omit the prototype on a system where sizeof(void*)!=sizeof(int),
you'll end up with broken object code with or without the cast.

IOW, omitting the cast doesn't really buy you anything worthwhile. OTOH,
including the cast makes it easier to visually catch cases such as:

struct foo *p;

/* one million LoC later */

p = (struct foo *) malloc(n * sizeof(struct bar));

Ioannis Vranos

unread,
Nov 18, 2009, 12:25:56 PM11/18/09
to
Richard wrote:

> Ioannis Vranos <wooj...@huskies.com> writes:
>
>> Michael Tsang wrote:
>>>
>>> 10. Use of malloc without casting is considered a poor practice (it is
>>> an error in C++). Cast it to suitable type instead.
>>
>> C and C++ are different languages.
>
> And you posted that why?


Because you said we should cast in C, because using malloc() needs a casting
in C++, where using malloc() is considered poor practice.

Ioannis Vranos

unread,
Nov 18, 2009, 12:27:18 PM11/18/09
to
Nobody wrote:
>
>
> IOW, omitting the cast doesn't really buy you anything worthwhile. OTOH,
> including the cast makes it easier to visually catch cases such as:
>
> struct foo *p;
>
> /* one million LoC later */
>
> p = (struct foo *) malloc(n * sizeof(struct bar));


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

Nobody

unread,
Nov 18, 2009, 12:29:36 PM11/18/09
to
On Wed, 18 Nov 2009 16:42:53 +0000, Richard Tobin wrote:

>>Sounds to me idiotic not to cast. Strong typing better than weak
>>typing.
>
> Casting is a way to defeat strong typing.
>
> int a;
> char *p;
> ...
> p = a;
>
> This is an error requiring a diagnostic.

But we were discussing casting a "void*", which is C's own opt-out of
static typing.

C doesn't care about either implicit or explicit casts of void* to other
pointers. An explicit cast at least provides a visual cue as to the
intent, and will even produce a diagnostic if you explicitly cast to the
wrong type, e.g.:

struct foo *p;
struct bar *q;
void *x;

p = x; /* no diagnostic */
p = (struct bar *) x; /* diagnostic */

Ioannis Vranos

unread,
Nov 18, 2009, 12:30:29 PM11/18/09
to
Ioannis Vranos wrote:

> Richard wrote:
>
>> Ioannis Vranos <wooj...@huskies.com> writes:
>>
>>> Michael Tsang wrote:
>>>>
>>>> 10. Use of malloc without casting is considered a poor practice (it is
>>>> an error in C++). Cast it to suitable type instead.
>>>
>>> C and C++ are different languages.
>>
>> And you posted that why?
>
>
> Because you said we should cast in C, because using malloc() needs a
> casting in C++, where using malloc() is considered poor practice.


More accurately bad style. Since malloc(), calloc()/free() do not invoke
object constructors/destructors respectively.

Nobody

unread,
Nov 18, 2009, 12:34:43 PM11/18/09
to
On Wed, 18 Nov 2009 07:57:16 -0800, Keith Thompson wrote:

> Ioannis's web page itself says:
>
> | Misconception 10: Invokations of malloc(), calloc(), and realloc(),
> | need casting.
> ...
> | Clarification: Casting is not needed
> ...

Should say:

Misconception 10: whether or not to cast the return value of malloc() etc
has a definitive answer and isn't at all controversial.
...
Clarification: asking whether or not to cast the return value of malloc()
etc will start a heated discussion with a 26% chance of degenerating into
an all-out flame-war.


Keith Thompson

unread,
Nov 18, 2009, 12:40:29 PM11/18/09
to
Ioannis Vranos <wooj...@huskies.com> writes:
> bartc wrote:
>>
>>
>> Why is it double- (and sometimes triple- and quadruple-) spaced? That
>> makes it hard to follow.
>
>
> The page looks OK in my laptop (1920x1080 resolution). :-)
>
>
>
>

But the code you've been posting here has been widely spaced.

I've preserved the blank lines in the above quotation.

>> The license section (about 60% of the bulk of the document) is a
>> distraction. Why not just make it a link.
>
> The license must be included in the document to be in effect.

Hmm. I wonder if it has to be in the web page itself, or if a web
page with a link to the license could be considered a single document.
Not a question for this newsgroup. Perhaps you could ask in
gnu.misc.discuss; they could use some actual non-flame posts.

Keith Thompson

unread,
Nov 18, 2009, 12:42:07 PM11/18/09
to
Nobody <nob...@nowhere.com> writes:
[...]

> C doesn't care about either implicit or explicit casts of void* to other
> pointers.
[...]

There's no such thing as an implicit cast. A cast is an explicit
conversion.

Richard

unread,
Nov 18, 2009, 12:49:00 PM11/18/09
to
Ioannis Vranos <wooj...@huskies.com> writes:

> Richard wrote:
>
>> Ioannis Vranos <wooj...@huskies.com> writes:
>>
>>> Michael Tsang wrote:
>>>>
>>>> 10. Use of malloc without casting is considered a poor practice (it is
>>>> an error in C++). Cast it to suitable type instead.
>>>
>>> C and C++ are different languages.
>>
>> And you posted that why?
>
> Because you said we should cast in C, because using malloc() needs a casting
> in C++, where using malloc() is considered poor practice.

No I did not.

And neither did he. He merely pointed out the situation in C++.

Believe it or not some people can discuss 2 tightly related languages
together.

Hallvard B Furuseth

unread,
Nov 18, 2009, 12:56:25 PM11/18/09
to
Keith Thompson writes:

> Michael Tsang <mik...@gmail.com> writes:
>> 10. Use of malloc without casting is considered a poor practice (it is an
>> error in C++). Cast it to suitable type instead.
>
> No, casting the result of malloc is considered poor practice in C.
> This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.

Except in cases when it isn't, also as covered by the FAQ:-)
Like if you want some code snippets compilable as both C and C++.

I like to classify this one under the rule "make wrong code look wrong",
quoting to Joel Spolsky:
http://www.joelonsoftware.com/articles/Wrong.html

This:

p = malloc(sizeof(struct foo));

is poor code because you have to check (or remember) the declaration of
p to see if it really has type struct foo, even though that easily could
have been avoided with one of these:

p = malloc(sizeof(*p));
p = (struct foo *) malloc(sizeof(struct foo));

In the latter case p might still have the wrong type, but at least
you can tell at a glance that the compiler will complain if so.

--
Hallvard

Hallvard B Furuseth

unread,
Nov 18, 2009, 1:07:26 PM11/18/09
to
Ioannis Vranos writes:
>bartc wrote:
>> Why is it double- (and sometimes triple- and quadruple-) spaced? That
>> makes it hard to follow.
>
> The page looks OK in my laptop (1920x1080 resolution). :-)

And if you remove most style and font stuff, use <pre> instead of <br>
and &nbsp; for formatting of code, it'll even look good on screens and
browsers with other setups than yours.

I also suggest to put the misconceptions in quotes, to visually separate
what you do not claim from what you do.

--
Hallvard

Nick

unread,
Nov 18, 2009, 1:46:04 PM11/18/09
to
gaz...@shell.xmission.com (Kenny McCormack) writes:

> In article <4431fa9c-e8a0-4dcc...@m38g2000yqd.googlegroups.com>,
> gwowen <gwo...@gmail.com> wrote:


>>On Nov 18, 1:40 pm, Tom St Denis <t...@iahu.ca> wrote:
>>
>>> In short, it's bad form to call functions without a prototype.
>>

>>So if I use a C99-mode compiler (or -Wmissing-prototypes or
>>equivalent), the major (sole?) reason for not casting vanishes, right?
>

> You are not allowed to discuss C99 in CLC...
>
> Seriously, the "not casting the return value of malloc()" shibboleth
> arose mainly out of C89 considerations (the only version approved by
> alpha male Dicky H).

Do you recommend I should rewrite:

int compare_strings(void *a,void *b) {
char *s1 = a;
char *s2 = b;
return strcmp(s1,s2);
}

as

int compare_strings(void *a,void *b) {
char *s1 = (char *)a;
char *s2 = (char *)b;
return strcmp(s1,s2);
}

If so, why? If not, why is the void pointer from malloc any different?
--
Online waterways route planner: http://canalplan.org.uk
development version: http://canalplan.eu

Default User

unread,
Nov 18, 2009, 1:56:02 PM11/18/09
to
Michael Tsang wrote:

> 10. Use of malloc without casting is considered a poor practice (it
> is an error in C++). Cast it to suitable type instead.

Use of malloc() is C++ is normally poor practice. There's a small
subset of writers who create code that needs to compile under both
languages. They should be concerned about cross-language compatibility.
Others should not.


Brian

--
Day 289 of the "no grouchy usenet posts" project

Seebs

unread,
Nov 18, 2009, 2:02:50 PM11/18/09
to
On 2009-11-18, gwowen <gwo...@gmail.com> wrote:
> So if I use a C99-mode compiler (or -Wmissing-prototypes or
> equivalent), the major (sole?) reason for not casting vanishes, right?

Not really. The big reason not to do it is that it's not necessary and
distracts from what you're doing.

int x = 0, *p;
char *s;

x += (int) 1;
s = (char *) "hello";
p = (int *) &x;
(void) assert(((char *) s)[(int) x] == (int) (char) 'e');

You get the idea.

-s
--
Copyright 2009, all wrongs reversed. Peter Seebach / usenet...@seebs.net
http://www.seebs.net/log/ <-- lawsuits, religion, and funny pictures
http://en.wikipedia.org/wiki/Fair_Game_(Scientology) <-- get educated!

Seebs

unread,
Nov 18, 2009, 2:05:13 PM11/18/09
to
On 2009-11-18, Nobody <nob...@nowhere.com> wrote:
> An explicit cast at least provides a visual cue as to the
> intent

What "intent" is that?

Seebs

unread,
Nov 18, 2009, 2:07:32 PM11/18/09
to
On 2009-11-18, Nobody <nob...@nowhere.com> wrote:
> Misconception 10: whether or not to cast the return value of malloc() etc
> has a definitive answer and isn't at all controversial.
> ...
> Clarification: asking whether or not to cast the return value of malloc()
> etc will start a heated discussion with a 26% chance of degenerating into
> an all-out flame-war.

I would endorse this answer as factually accurate.

Seebs

unread,
Nov 18, 2009, 2:11:00 PM11/18/09
to
On 2009-11-18, Hallvard B Furuseth <h.b.fu...@usit.uio.no> wrote:
> p = malloc(sizeof(*p));
> p = (struct foo *) malloc(sizeof(struct foo));

> In the latter case p might still have the wrong type, but at least
> you can tell at a glance that the compiler will complain if so.

In the former case, you've guaranteed that it'll be the right type no
matter what. In the latter case, you've invited a maintenance programmer
to later change it to:

p = (struct bar *) malloc(some stuff I didn't read);

If the compiler doesn't notice that, then the maintenance programmer is
probably done.

Eric Sosman

unread,
Nov 18, 2009, 2:34:41 PM11/18/09
to
gwowen wrote:
> On Nov 18, 1:40 pm, Tom St Denis <t...@iahu.ca> wrote:
>
>> In short, it's bad form to call functions without a prototype.
>
> So if I use a C99-mode compiler (or -Wmissing-prototypes or
> equivalent), the major (sole?) reason for not casting vanishes, right?

A C99 compiler must complain about an attempt to call a
function that has not been declared. It need not complain
about a call to a function that has been declared with no
prototype. From my reading of the info, -Wmissing-prototypes
controls a gcc complaint at the point where the function is
defined, not where it is called; -Wimplicit-function-declaration
is probably the flag you're thinking of.

But yes: With suitable compiler versions and/or flags, this
reason for omitting the cast on malloc() disappears. Isn't that
the wrong question, though? Why search for reasons to remove
extraneous baggage; if the baggage is of no use, it shouldn't
have been there to begin with!

#include <stdio.h>
#define VSUPPRESS 1
int (main)(void) {
{\
(*(int (*)(const char*,...))(printf))
(((char*)"Hello, world!""\n"))
}\
return (42), 0;
#if VSUPPRESS
}
#undef SUPPRESSV
#else
#endif

--
Eric Sosman
eso...@ieee-dot-org.invalid

Richard Harter

unread,
Nov 18, 2009, 3:12:05 PM11/18/09
to

Yu have to appreciate that Kenny doesn't care about the actual
issues of writing and using C. His chosen function is mocking
the "regulars". In his fantasy world Heathfield is a Svengali
figure who dominates c.l.c with an in-group clique. According to
Kenny the regulars have nothing of consequence to say about C;
rather they spend their time putting down the pretensions of
inferiors by pointing out clique nominated coding errors.

Kenny will be happy to list them for you - he does it as a
regular thing. They include such things as void main(), casting
malloc, i = i++, etc. Kenny doesn't care whether they are coding
errors or not - as far as I can tell he doesn't have any interest
in C as such. To him the "errors" in his little list are
shibboleths, tokens by which the insiders know each other and
establish their credentials.


Richard Harter, c...@tiac.net
http://home.tiac.net/~cri, http://www.varinoma.com
Infinity is one of those things that keep philosophers busy when they
could be more profitably spending their time weeding their garden.

Richard

unread,
Nov 18, 2009, 3:16:55 PM11/18/09
to
c...@tiac.net (Richard Harter) writes:

> On Wed, 18 Nov 2009 18:46:04 +0000, Nick
> <3-no...@temporary-address.org.uk> wrote:
>
>>gaz...@shell.xmission.com (Kenny McCormack) writes:
>>
>>> In article <4431fa9c-e8a0-4dcc...@m38g2000yqd.googlegroups.com>,
>>> gwowen <gwo...@gmail.com> wrote:

Kenny is quite correct.

Hallvard B Furuseth

unread,
Nov 18, 2009, 3:20:58 PM11/18/09
to
Seebs writes:
> On 2009-11-18, Hallvard B Furuseth <h.b.fu...@usit.uio.no> wrote:
>> p = malloc(sizeof(*p));
>> p = (struct foo *) malloc(sizeof(struct foo));
>
>> In the latter case p might still have the wrong type, but at least
>> you can tell at a glance that the compiler will complain if so.
>
> In the former case, you've guaranteed that it'll be the right type no
> matter what.

Unless, as I just mentioned, you need the code to compile as C++.
Also the "right type" isn't of any help if p is void*.

But sure, I normally prefer the former version too.

> In the latter case, you've invited a maintenance programmer
> to later change it to:
>
> p = (struct bar *) malloc(some stuff I didn't read);

And in the former case I've "invited" the maintenance programmer to
change it to:

r = malloc(some stuff I didn't read);

except I don't invite maintenance programmers to not even look at the
entire line they change.

Incidentally, if he changes the type of p from void* to struct bar*, it
is the second version and not the first which the compiler will catch.


Anyway, my point was that with all four versions above (the originals
and the broken "maintaned" code), you only need to look at a single line
in isolation regarding this particular bug. Which makes a bug fairly
noticable. With

p = malloc(sizeof(struct foo));

you need to look in two different places to see if there is a bug - the
malloc line and the declaration.

--
Hallvard

Seebs

unread,
Nov 18, 2009, 3:22:03 PM11/18/09
to
On 2009-11-18, Hallvard B Furuseth <h.b.fu...@usit.uio.no> wrote:
>> On 2009-11-18, Hallvard B Furuseth <h.b.fu...@usit.uio.no> wrote:
>>> p = malloc(sizeof(*p));
>>> p = (struct foo *) malloc(sizeof(struct foo));

>> In the former case, you've guaranteed that it'll be the right type no
>> matter what.

> Unless, as I just mentioned, you need the code to compile as C++.

Which is bad style to begin with. :)

> Also the "right type" isn't of any help if p is void*.

In which case, you're probably doing something wrong.

>> p = (struct bar *) malloc(some stuff I didn't read);
>
> And in the former case I've "invited" the maintenance programmer to
> change it to:
>
> r = malloc(some stuff I didn't read);
>
> except I don't invite maintenance programmers to not even look at the
> entire line they change.

You are very optimistic.

> Incidentally, if he changes the type of p from void* to struct bar*, it
> is the second version and not the first which the compiler will catch.

True.

> Anyway, my point was that with all four versions above (the originals
> and the broken "maintaned" code), you only need to look at a single line
> in isolation regarding this particular bug. Which makes a bug fairly
> noticable. With

> p = malloc(sizeof(struct foo));

> you need to look in two different places to see if there is a bug - the
> malloc line and the declaration.

True. In practice, I've never had it be an issue -- if I'm calling malloc,
I'm usually visibly using the thing in a way which matches the usage.

Basically, I've seen more people show up with weird crashes due to a
cast malloc than due to an uncast one.

Richard

unread,
Nov 18, 2009, 3:27:47 PM11/18/09
to
Seebs <usenet...@seebs.net> writes:

I don't believe you for one minute. I have NEVER seen a crash due to a
cast to a perfectly valid destination variable of that type.

Keith Thompson

unread,
Nov 18, 2009, 3:29:38 PM11/18/09
to
Hallvard B Furuseth <h.b.fu...@usit.uio.no> writes:
> Keith Thompson writes:
>> Michael Tsang <mik...@gmail.com> writes:
>>> 10. Use of malloc without casting is considered a poor practice (it is an
>>> error in C++). Cast it to suitable type instead.
>>
>> No, casting the result of malloc is considered poor practice in C.
>> This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.
>
> Except in cases when it isn't, also as covered by the FAQ:-)
> Like if you want some code snippets compilable as both C and C++.

I know of only two cases where casting the result of malloc in C
makes sense.

One is when you need to compile the same code as both C and C++.
Given C++'s ability to interface to compiled C code, this is
very rarely necessary. (It can make sense for header files to be
compatible, but header files shouldn't contain calls to malloc.)

The other is when you're stuck using a pre-ANSI implementation
in which malloc() returns char* rather than void*. This also is
vanishingly rare -- and such old compilers are likely to allow an
implicit conversion from char* to some_type* anyway.

Nearly all style rules are conditional, in the sense that once you
understand why the rule makes sense, you can justify breaking it in
some cases.

> I like to classify this one under the rule "make wrong code look wrong",
> quoting to Joel Spolsky:
> http://www.joelonsoftware.com/articles/Wrong.html
>
> This:
>
> p = malloc(sizeof(struct foo));
>
> is poor code because you have to check (or remember) the declaration of
> p to see if it really has type struct foo,

Agreed.

> even though that easily could
> have been avoided with one of these:
>
> p = malloc(sizeof(*p));
> p = (struct foo *) malloc(sizeof(struct foo));
>
> In the latter case p might still have the wrong type, but at least
> you can tell at a glance that the compiler will complain if so.

And what advantage does the second form have over the first? (Hint:
None at all.) The second form lets you detect a type mismatch
at compile time, but only if the two occurrences of "struct foo"
are kept in synch. The first avoids the possibility of a type
mismatch in the first place (again, if both occurrences of "p" are
kept in synch, but IMHO that's easier to do if you're accustomed
to the idiom).

Casts in general are potentially dangerous, since the bypass type
checking. If you get into the habit of using casts as little as
possible, it's easier to verify that the few you do use actually
make sense. The more casts you use, the harder this is.

Keith Thompson

unread,
Nov 18, 2009, 3:30:44 PM11/18/09
to
Seebs <usenet...@seebs.net> writes:
> On 2009-11-18, Nobody <nob...@nowhere.com> wrote:
>> Misconception 10: whether or not to cast the return value of malloc() etc
>> has a definitive answer and isn't at all controversial.
>> ...
>> Clarification: asking whether or not to cast the return value of malloc()
>> etc will start a heated discussion with a 26% chance of degenerating into
>> an all-out flame-war.
>
> I would endorse this answer as factually accurate.

Yes, it's factually accurate, but less *useful* than an answer that
discourages C programmers from cating the result of malloc().

jacob navia

unread,
Nov 18, 2009, 3:43:24 PM11/18/09
to
Richard Harter a �crit :

>
> Yu have to appreciate that Kenny doesn't care about the actual
> issues of writing and using C.

If you care to search in the archives, Kenny has sometimes given
very good answers to questions posed here.

> His chosen function is mocking
> the "regulars".

Yes, That is why I think he is a good poster here.

> In his fantasy world Heathfield is a Svengali
> figure who dominates c.l.c with an in-group clique.

That analysis is correct.

> According to
> Kenny the regulars have nothing of consequence to say about C;
> rather they spend their time putting down the pretensions of
> inferiors by pointing out clique nominated coding errors.
>

I have posted code here, proposing a container library for C.
Heathfield answered that he did not want to be involved
"with a looser" and never participated in a meaningful way
in those discussions. Neither Mr Thompson, nor most of the
clique in c.l.c. They have nothing to say about an improvement
of C, or about software engineering or about just anything
positive.

Iwas surprised that the standards committee decided to fix asctime(),
and I suspect strongly that my personal campaign against it was
one of the reasons the committee decided to fix it. Heathfield and
the others of the clique were always trying to justify asctime()
misgivings or downplaying the issue's importantce.

What the evolution of C is concerned, Heathfield (and Co) are
always complaining that standard C is not widely implemented,
ignoring all the implementations of the standard. Heathfield
uses a compiler version from the last century, and then it says
that gcc doesn't implement C99 even if he knows (as everybody
else) that C99 is quite well implemented in gcc, in the
linux versions at least.

> Kenny will be happy to list them for you - he does it as a
> regular thing. They include such things as void main(), casting
> malloc, i = i++, etc.

Thousands of messages about those "questions" pollute this group
and the insistence of the regulars to discuss those "issues"
AD NAUSEAM makes this group specially boring.

In my posts I try to improve the technical level of this group by discussing
interfaces, ways of doing things, abstract data types, etc. Neither
Mr Thompson nor Mr Heathfield are ever present in those discussions.

Obvious.

What could they possibly say?


> Kenny doesn't care whether they are coding
> errors or not - as far as I can tell he doesn't have any interest
> in C as such.

This is your unjustified personal opinion. I could say that YOU
have no interest in C either. You never bring your code here, or
bring subjects about programming in C in general. Can you please
tell me when was the last time you proposed something to discuss here?

Thanks.


> To him the "errors" in his little list are
> shibboleths, tokens by which the insiders know each other and
> establish their credentials.

Obviously there are many other errors that could be dicussed. But
they aren't. Only those are selected, to recognize who is a member
of their group.

> Infinity is one of those things that keep philosophers busy when they
> could be more profitably spending their time weeding their garden.

Weeding the garden is the activity of failed philosophers, unable to
grasp what makes us human: Infinity.

Seebs

unread,
Nov 18, 2009, 3:42:25 PM11/18/09
to
On 2009-11-18, Keith Thompson <ks...@mib.org> wrote:
> Seebs <usenet...@seebs.net> writes:
>> On 2009-11-18, Nobody <nob...@nowhere.com> wrote:
>>> Misconception 10: whether or not to cast the return value of malloc() etc
>>> has a definitive answer and isn't at all controversial.
>>> ...
>>> Clarification: asking whether or not to cast the return value of malloc()
>>> etc will start a heated discussion with a 26% chance of degenerating into
>>> an all-out flame-war.

>> I would endorse this answer as factually accurate.

> Yes, it's factually accurate, but less *useful* than an answer that
> discourages C programmers from cating the result of malloc().

That depends! In terms of amount of programmer time wasted, I'd guess
that making a recommendation costs more than either answer does. :P

Seebs

unread,
Nov 18, 2009, 3:52:54 PM11/18/09
to
On 2009-11-18, jacob navia <ja...@nospam.org> wrote:
> If you care to search in the archives, Kenny has sometimes given
> very good answers to questions posed here.

He has, occasionally.

>> His chosen function is mocking
>> the "regulars".

> Yes, That is why I think he is a good poster here.

This undermines my confidence in you, actually.

>> In his fantasy world Heathfield is a Svengali
>> figure who dominates c.l.c with an in-group clique.

> That analysis is correct.

I don't buy it at all.

> I have posted code here, proposing a container library for C.

Yes.

And I gave you detailed explanations of why I thought it was the wrong
problem to solve, and a solution to this problem would not be of great
value to many C programmers. You may not agree with those explanations,
but you can't deny that I engaged at some length to talk about them.

> Heathfield answered that he did not want to be involved
> "with a looser" and never participated in a meaningful way
> in those discussions. Neither Mr Thompson, nor most of the
> clique in c.l.c. They have nothing to say about an improvement
> of C, or about software engineering or about just anything
> positive.

Even assuming we just sort of randomly guess at who you think is "the
clique", I don't think I buy that. I've seen long discussions from
all of these people about C, and about proposed improvements to C.

Don't mistake disagreeing with you about what would be an improvement
for disinterest in improvements.

> Iwas surprised that the standards committee decided to fix asctime(),
> and I suspect strongly that my personal campaign against it was
> one of the reasons the committee decided to fix it.

This would be pretty surprising to me, simply because my experience was
that the committee looked at defect reports, not at posts on Usenet.

> Heathfield and
> the others of the clique were always trying to justify asctime()
> misgivings or downplaying the issue's importantce.

Unless I misremember, the "fix" is simply to point out that, yes, it's
possible for the sample implementation given to produce undefined behavior
in some circumstances, and yes, here's what those circumstances are.

I wouldn't consider this a "fix" myself.

On the other hand, I haven't used asctime in over 15 years, and it was on
the list of things, like gets, that I consider it an error for someone to
use.

> What the evolution of C is concerned, Heathfield (and Co) are
> always complaining that standard C is not widely implemented,
> ignoring all the implementations of the standard.

Huh. I guess I'm not part of "and Co", then, because I use C99 features
without really paying attention to them. They work widely enough fo me.

> Heathfield
> uses a compiler version from the last century, and then it says
> that gcc doesn't implement C99 even if he knows (as everybody
> else) that C99 is quite well implemented in gcc, in the
> linux versions at least.

It's not complete, though, so if someone asked me whether it supported
C99, I'd say "not completely, but it seems to do pretty well."

> Thousands of messages about those "questions" pollute this group
> and the insistence of the regulars to discuss those "issues"
> AD NAUSEAM makes this group specially boring.

Well, one solution would be to figure out how to get people to stop posting
nonsense about them. If you can do that, poof, they go away.

> In my posts I try to improve the technical level of this group by discussing
> interfaces, ways of doing things, abstract data types, etc. Neither
> Mr Thompson nor Mr Heathfield are ever present in those discussions.

Except you just pointed out how Heathfield participated in a previous one.
That you didn't like or agree with his participation doesn't mean he didn't
offer a technical opinion.

>> Kenny doesn't care whether they are coding
>> errors or not - as far as I can tell he doesn't have any interest
>> in C as such.

> This is your unjustified personal opinion. I could say that YOU
> have no interest in C either.

But there'd be a big difference, which is that it'd be obviously wrong --
he posts about C fairly often.

> You never bring your code here, or
> bring subjects about programming in C in general. Can you please
> tell me when was the last time you proposed something to discuss here?

Not all discussion has to be proposals of discussions. Right now, the C
stuff I'm working on is nearly all system-dependent, so I don't have much
new to say about C in general, but I like to hang out so I can answer
peoples' questions and try to get them unstuck.

> Obviously there are many other errors that could be dicussed. But
> they aren't. Only those are selected, to recognize who is a member
> of their group.

This makes no sense. None of the people you accuse of this start these
discussions. These are, after all, FAQs -- because people keep asking
them.

But hey, maybe we should do an experiment. You claim that this clique is
obvious.

Okay. How about the people who think it's obvious each, independently, write
down a list of the members of the clique, and the positions which are agreed
upon by all those members. I doubt you'd end up with enough agreement for
people to find it persuasive, even if we ignore the fact that many of your
statements about what other people say or do are flatly incorrect.

Richard Harter

unread,
Nov 18, 2009, 3:59:28 PM11/18/09
to
On Wed, 18 Nov 2009 21:16:55 +0100, Richard <rgr...@gmail.com>
wrote:

You only say that because Kenny has clouded your mind.

Keith Thompson

unread,
Nov 18, 2009, 4:31:49 PM11/18/09
to
jacob navia <ja...@nospam.org> writes:
[...]

> I have posted code here, proposing a container library for C.
> Heathfield answered that he did not want to be involved
> "with a looser" and never participated in a meaningful way
> in those discussions.

I certainly don't recall Richard Heathfield ever referring to you
as a loser (or a looser). Your use of quotation marks implies
that it's something he actually wrote. You should either support
this claim with a citation of the article in which he said this,
or retract it. I don't seriously expect you to do either.

> Neither Mr Thompson, nor most of the
> clique in c.l.c. They have nothing to say about an improvement
> of C, or about software engineering or about just anything
> positive.

You can repeat this as often as you like. It's still not true.
(I'm not going to say it's a lie; it's conceivable that you actually
believe it.)

You posted "Proposal for the C library in the new standard"
in comp.std.c on 2009-04-19. Of the 44 articles in the thread,
4 were mine.

You posted "Past overflow discussion" in comp.std.c on comp.lang.c
on 2009-09-04. Of the 33 articles in the thread, 4 were mine.

You posted "Zero overhead overflow checking" in comp.std.c and
comp.lang.c on 2009-09-07. Of the 110 articles in the thread,
22 were mine.

You posted "Updated proposal for overflow handling" in comp.std.c
on 2009-09-11. Mine was the only response.

And so on.

[...]

> In my posts I try to improve the technical level of this group by discussing
> interfaces, ways of doing things, abstract data types, etc. Neither
> Mr Thompson nor Mr Heathfield are ever present in those discussions.
>
> Obvious.
>
> What could they possibly say?

See above.

[...]

Walter Banks

unread,
Nov 18, 2009, 4:52:19 PM11/18/09
to

jacob navia wrote:

> I was surprised that the standards committee decided to fix asctime(),


> and I suspect strongly that my personal campaign against it was
> one of the reasons the committee decided to fix it.

WG14 needs a paper trail to support arguments for change either
through defect reports to resolve ambiguities or formal documents
to make changes in the standard.

w..


Nick

unread,
Nov 18, 2009, 5:49:51 PM11/18/09
to
Walter Banks <wal...@bytecraft.com> writes:

So, another 7 posts of the same old crowd (on both side) and f-all
about C again. Can you *all* leave it out, guys?

Message has been deleted

Richard Harter

unread,
Nov 18, 2009, 6:20:40 PM11/18/09
to
On Wed, 18 Nov 2009 22:49:51 +0000, Nick
<3-no...@temporary-address.org.uk> wrote:

>Walter Banks <wal...@bytecraft.com> writes:
>
>> jacob navia wrote:
>>
>>> I was surprised that the standards committee decided to fix asctime(),
>>> and I suspect strongly that my personal campaign against it was
>>> one of the reasons the committee decided to fix it.
>>
>> WG14 needs a paper trail to support arguments for change either
>> through defect reports to resolve ambiguities or formal documents
>> to make changes in the standard.
>
>So, another 7 posts of the same old crowd (on both side) and f-all
>about C again. Can you *all* leave it out, guys?

I would have thought it obvious that they can't. As a piece of
advice, the food fight has been going on for quite some time.
The participants won't stop. Either ignore them or participate
just as you choose.

Richard Heathfield

unread,
Nov 18, 2009, 6:45:22 PM11/18/09
to

> On 2009-11-18, Nobody <nob...@nowhere.com> wrote:
>> An explicit cast at least provides a visual cue as to the
>> intent
>
> What "intent" is that?

The intent to put unnecessary barriers in the way of readability.

--
Richard Heathfield <http://www.cpax.org.uk>
Email: -http://www. +rjh@
"Usenet is a strange place" - dmr 29 July 1999
Sig line vacant - apply within

robert...@yahoo.com

unread,
Nov 18, 2009, 6:59:18 PM11/18/09
to
On Nov 18, 5:02 am, Richard Heathfield <r...@see.sig.invalid> wrote:
> In <he0j5r$ai...@aioe.org>, jacob navia wrote:
>
> > Richard Tobin a écrit :
> >> In article <slrnhg763j.76k.usenet-nos...@guild.seebs.net>,
> >> Seebs  <usenet-nos...@seebs.net> wrote:
>
> >>> Use of malloc with a cast regularly hides errors that should have
> >>> been caught by the compiler.
>
> >> Much less of a problem now that compilers generally warn about
> >> undeclared functions.
>
> >> -- Richard
>
> > C++ NEEDS the cast... If you ever want to compile your code in C++
> > mode it is better to leave the cast there.
>
> Better still, remove both the cast and the call, and replace it with
> new or new[].


Aside from the missing-prototype issue a type for the return from the
allocation function. Something like:

#define CALLOC_TYPE(type) ((type*)calloc(1, sizeof(type)))
#define CALLOC_ARRAY(count, type) ((type*)calloc(count, sizeof(type)))

(and probably malloc versions as well).

Those would probably take care of most actual allocations, and help
prevent type errors. And of course the raw functions remain
available, if those better serve the purpose.

Richard Harter

unread,
Nov 18, 2009, 7:00:16 PM11/18/09
to
On Wed, 18 Nov 2009 21:43:24 +0100, jacob navia
<ja...@nospam.org> wrote:

>Richard Harter a �crit :
>>
>> Yu have to appreciate that Kenny doesn't care about the actual
>> issues of writing and using C.
>
>If you care to search in the archives, Kenny has sometimes given
>very good answers to questions posed here.

I'm sure you believe that.

>
>> His chosen function is mocking
>> the "regulars".
>
>Yes, That is why I think he is a good poster here.
>
>> In his fantasy world Heathfield is a Svengali
>> figure who dominates c.l.c with an in-group clique.
>
>That analysis is correct.

I'm sure that you that also.

[snip whining]

>> Infinity is one of those things that keep philosophers busy when they
>> could be more profitably spending their time weeding their garden.
>
>Weeding the garden is the activity of failed philosophers, unable to
>grasp what makes us human: Infinity.

Chortle. For that you are more than forgiven.

Richard Heathfield

unread,
Nov 18, 2009, 7:15:17 PM11/18/09
to
In <he1m88$o99$1...@aioe.org>, jacob navia wrote:

> Richard Harter a �crit :
>>
>> Yu have to appreciate that Kenny doesn't care about the actual
>> issues of writing and using C.
>
> If you care to search in the archives, Kenny has sometimes given
> very good answers to questions posed here.

Cite, please.

<snip>

>> In his fantasy world Heathfield is a Svengali
>> figure who dominates c.l.c with an in-group clique.
>
> That analysis is correct.

In your opinion, perhaps, but not in mine.

>> According to
>> Kenny the regulars have nothing of consequence to say about C;
>> rather they spend their time putting down the pretensions of
>> inferiors by pointing out clique nominated coding errors.
>>
>
> I have posted code here, proposing a container library for C.
> Heathfield answered that he did not want to be involved
> "with a looser" and never participated in a meaningful way
> in those discussions.

Actually, IIRC I pointed out that an attempt had been made a few years
back to put together a "comp.lang.c library", but the project got
bogged down in arguments about how portable it should be. I guessed
that something of the kind might happen, and didn't get involved. It
did not seem unreasonable to me to guess that the same problem might
recur this time round, so again I decided not to get involved. I also
mentioned at that time that I was contemplating posting the source to
my own library in the hope of some constructive comments, but I
hadn't yet decided whether to do that. I still haven't.

> Neither Mr Thompson, nor most of the
> clique in c.l.c. They have nothing to say about an improvement
> of C, or about software engineering or about just anything
> positive.

Improvements to the language are better discussed in comp.std.c.
Nevertheless, Keith does occasionally make comments along the lines
of "it would be nice if".

<snip>

> Heathfield and the others of the clique were always trying to
> justify asctime() misgivings or downplaying the issue's importantce.

I don't think anyone actually uses it, so it's hard to see how it
might be important.

> What the evolution of C is concerned, Heathfield (and Co) are
> always complaining that standard C is not widely implemented,

C89 is extraordinarily widely implemented. C99 is not.

> ignoring all the implementations of the standard.

Six, I believe.

> Heathfield
> uses a compiler version from the last century,

The compilers I use on a fairly regular basis are:

gcc 2.95.3 (this century, just)
Microsoft Visual C (this century)
Borland C (this century)
Digital Mars (this century)
Microsoft Visual C (last century - ca. 1998)
Turbo C++ (last century - ca. 1991)
Turbo C (last century - ca. 1988)

So, on average, you're slightly less than half-right.

> and then it says
> that gcc doesn't implement C99 even if he knows (as everybody
> else) that C99 is quite well implemented in gcc, in the
> linux versions at least.

My claim is that GNU's compiler does not conform to C99, which is
still true, strictly speaking. I am perfectly happy to agree that
it's *nearly* there - but it is not there *yet*. When it *is* there,
it will be a major step forward for C99.

<snip>

> In my posts I try to improve the technical level of this group by
> discussing interfaces, ways of doing things, abstract data types,
> etc. Neither Mr Thompson nor Mr Heathfield are ever present in those
> discussions.

So you have forgotten who it was who suggested to you the idea of
side-channel data in constructors, comparators, and iterators? The
idea that you liked and said you'd adopt?

<snip>

>> To him the "errors" in his little list are
>> shibboleths, tokens by which the insiders know each other and
>> establish their credentials.
>
> Obviously there are many other errors that could be dicussed.

When they are made, they are discussed (if spotted, which I suppose
isn't always the case).

> But they aren't. Only those are selected, to recognize who is a
> member of their group.

The group is called comp.lang.c, and every subscriber is a member
thereof. As for shibboleths, I think that's just nonsense - I for one
would welcome a few new subjects for discussion. That is why I am in
favour of (slightly) widening the topic of this group.

<snip>

Keith Thompson

unread,
Nov 18, 2009, 7:09:22 PM11/18/09
to
r...@zedat.fu-berlin.de (Stefan Ram) writes:
> Ioannis Vranos <wooj...@huskies.com> writes:
>>I have created a text available under GNU FDL 3 (Free
>>Documenation License) or later, regarding "Common
>>misconceptions about C" (C95).
>
> »This second edition cancels and replaces the first
> edition, ISO/IEC 9899:1990, as amended and corrected by
> ISO/IEC 9899/COR1:1994, ISO/IEC 9899/AMD1:1995, and
> ISO/IEC 9899/COR2:1996.«
>
> ISO/IEC 9899:1999 (E)
>
> This means that C is the language specified by ISO/IEC
> 9899:1999 (E). »ISO/IEC 9899:1990« is canceled.

In theory, yes. In practice, conforming C90 compilers are still
much more common than conforming C99 compilers. Many compilers
implement large parts of C99, but others, still in common use,
implement almost none of it (more precisely, almost none of the
differences between C90 and C99).

Kenny McCormack

unread,
Nov 18, 2009, 8:56:32 PM11/18/09
to
In article <4b045021....@text.giganews.com>,
Richard Harter <c...@tiac.net> excellently summarized the state of
affairs that constitute comp.lang.c, thusly - very charitably
attributing all this wisdom to yours truly:
...
>You have to appreciate that Kenny doesn't care about the actual

>issues of writing and using C. His chosen function is mocking
>the "regulars". In his fantasy world Heathfield is a Svengali
>figure who dominates c.l.c with an in-group clique. According to
>Kenny the regulars have nothing of consequence to say about C;
>rather they spend their time putting down the pretensions of
>inferiors by pointing out clique nominated coding errors.
>
>Kenny will be happy to list them for you - he does it as a
>regular thing. They include such things as void main(), casting
>malloc, i = i++, etc. Kenny doesn't care whether they are coding
>errors or not - as far as I can tell he doesn't have any interest
>in C as such. To him the "errors" in his little list are
>shibboleths, tokens by which the insiders know each other and
>establish their credentials.

Well done. 5 star post by Mr. Harter (5 bonus points there, right Richard?)

Kenny McCormack

unread,
Nov 18, 2009, 9:57:00 PM11/18/09
to
In article <87my2js...@temporary-address.org.uk>,
Nick <3-no...@temporary-address.org.uk> wrote:
...

>If so, why? If not, why is the void pointer from malloc any different?

Mr. Harter is quite correct in saying that I don't care one way or the
other about the C stuff. The reasons for this are complex and deep; my
plan is to reply to your other thread in which you inquire as to my
motives. If I work up the energy, I will post there. Until, you'll
just have to trust your imagination...

spinoza1111

unread,
Nov 18, 2009, 10:03:02 PM11/18/09
to
On Nov 18, 8:08 pm, Walter Banks <wal...@bytecraft.com> wrote:
> spinoza1111wrote:
> > >      General observation: There are quite a few misconceptions
> > > about C that you have not touched upon, like "An int has 32
> > > bits" and "Pointers are faster than array indices" and "The
>
> > Why is it not the case that pointers are faster than array indices?
>
> > Are they not-faster some of the time, or are they not-faster all of
> > the time?
>
> Start with some basic metrics. Count cycles and generated code.
>
> a) Take the half dozen or so cases and hand code them up as
>     micro operations and
>
> b) then separate all those micro operations that can be done at
>     compile time and those that must be done at run time
>
> c) Map the micro operations on the instruction set you are using
>     and count cycles  and bytes.
>
> The most significant differences will be the base address of an
> array is generally a constant that can often be optimized out
> with instruction selection or compile time math.
>
> Constant index references are generally a big win for arrays
> in most execution environments
>
> You really probably should have finished your book. Code
> generation and optimization are about 90% of creating a
> compiler. This stuff is pretty fundamental to that process.

Bullshit. If you don't understand parsing, the compiler is worthless.
And if you don't understand modern language design, the compiler is
even more worthless. Kernighan and Pike didn't understand modern
language design in 1970, because their mistakes in designing C
(aliasing, the preprocessor, the use of magic libraries, a broken
pseudo-for, pre-increment and post-increment not thought out in terms
of sequence, no strings, no characters properly understood, an integer
thought to have 16 bits in the original edition, braces used instead
of begin and end keywords at a time when braces weren't even available
on many keytops, two different ways of talking about arrays, etc)
became ... drum roll ... modern language design, rule one of which is
"please, don't EVER do another C".

Please, do not reinvent C
One such language was enough for me
One such language is enough for thee
One such language is enough for such as we
Are. Stay far
Away from C.
Oh say can you see
Any creeps who love C?
It's JUST a good way
Of hiding incompetency.

Old Basic was a better language and old Basic was a bad language. The
conclusion follows, directly.

Oh yes, and I did finish my book. It is available in stores and you
need to buy a copy. I'd send you a courtesy copy if you deserved one,
but you do not. It covers optimization and spends a whole chapter on
code generation for .Net, but the real meat is parsing since if you
screw up parsing there's not point in either code generation or
optimization, is there now?
>
> Regards,
>
> --
> Walter Banks
> Byte Craft Limitedhttp://www.bytecraft.com

spinoza1111

unread,
Nov 18, 2009, 10:11:49 PM11/18/09
to
On Nov 18, 6:44 pm, jacob navia <ja...@nospam.org> wrote:
> Richard Tobin a écrit :
>
> > In article <slrnhg763j.76k.usenet-nos...@guild.seebs.net>,
> > Seebs  <usenet-nos...@seebs.net> wrote:
>
> >> Use of malloc with a cast regularly hides errors that should have been
> >> caught by the compiler.
>
> > Much less of a problem now that compilers generally warn about
> > undeclared functions.
>
> > -- Richard
>
> C++ NEEDS the cast... If you ever want to compile your code in C++ mode
> it is better to leave the cast there.

I can't believe that NOT using the cast is a fashion statement. We
know that strong typing is more reliable than weak typing. We also
know that "efficiency" of computation in the sense of a metaphorical
speed is not something as important as its correctness, and that lowly
technicians overrate speed out of a childish attraction to the
computer-as-toy.

Tom St Denis

unread,
Nov 18, 2009, 10:16:02 PM11/18/09
to
On Nov 18, 6:59 pm, "robertwess...@yahoo.com"

Yeah but it still misses the problem that without a definition the
compiler won't know if it needs to convert parameters to the right
data type. malloc() needs a parameter that is of size_t size. How is
the compiler to know this?

The reason the casts are bad is it silences a warning that points out
you are calling a function without a proper prototype.

To the C++ crowd, if you mix C and C++ in a project, put your C code
in .c files and have your make system not explicitly call the C++
compiler for them. Build it in C mode, it's C code.

Tom

spinoza1111

unread,
Nov 18, 2009, 10:17:52 PM11/18/09
to
On Nov 18, 11:57 pm, Keith Thompson <ks...@mib.org> wrote:
> Lowell Gilbert <lguse...@be-well.ilk.org> writes:
> > Seebs <usenet-nos...@seebs.net> writes:

> >> On 2009-11-18, Michael Tsang <mikl...@gmail.com> wrote:
> >>> 10. Use of malloc without casting is considered a poor practice
>
> >> This is false.
>
> > Precisely.  That's why it belongs on a list of misconceptions.
>
> Michael Tsang was claiming that the use of malloc without a cast *is*
> considered poor practice.  Seebs was disagreeing with him (as did I).

"As did I", you say, with a sigh
But you cannot say why.
Malloc with a cast may hide your stupid errors
So you omit the cast in hopes this will ease your nighty-time terrors.
The problem is clear, my dear
Boy.
You're using a programming language, C
That became fashionable only because it came from
Princeton University.

>
> Ioannis's web page itself says:
>
> | Misconception 10: Invokations of malloc(), calloc(), and realloc(),
> | need casting.
> ...
> | Clarification: Casting is not needed
> ...

Richard

unread,
Nov 18, 2009, 11:53:52 PM11/18/09
to
gaz...@shell.xmission.com (Kenny McCormack) writes:

Indeed.

spinoza1111

unread,
Nov 19, 2009, 12:45:09 AM11/19/09
to
On Nov 19, 12:42 am, rich...@cogsci.ed.ac.uk (Richard Tobin) wrote:
> In article <d8708124-3045-489b-ae2e-c90aebf63...@f20g2000prn.googlegroups.com>,
>
> spinoza1111 <spinoza1...@yahoo.com> wrote:
> >Sounds to me idiotic not to cast. Strong typing better than weak
> >typing.
>
> Casting is a way to defeat strong typing.
>
>    int a;
>    char *p;
>    ...
>    p = a;
>
> This is an error requiring a diagnostic.
>
>    int a;
>    char *p;
>    ...
>    p = (char *)a;
>
> This is not.  The cast tells the compiler *not* to apply its usual
> strong typing, but to convert the value to a character pointer
> regardless.

Agreed.

The problem here is that it's possible to "know" C without actually
knowing how to program, which would IMO include sensitivity to types
and in general meaning. As it is, most CLCers here, with the exception
of you and Kenny for the most part, are without being aware of it
stuck in a logical atomism in which there are no distinctions of type:
shoes and ships and sealing wax are all the same to them.

That's what makes this newsgroup a simulation of the Mad Hatter's tea
party in Alice in Wonderland. Carroll anticipated the madness of the
20th century and one of its madnesses was the elimination of the
notion that there are incommensurate types of being. Capitalism, after
all, had through the commodity relationship made it possible to equate
all men and all things through the cash nexus, so it seems natural for
the C programmer, incompetent as a person and programmer in direct
proportion, usually, to his expertise in C, to want to use snoid
pointers, that point to his favorite space: a space in which there are
no distinctions of type: the space of the autistic child who can then
impose his private order on that space.
>
> -- Richard
> --
> Please remember to mention me / in tapes you leave behind.

spinoza1111

unread,
Nov 19, 2009, 12:50:06 AM11/19/09
to
On Nov 19, 1:21 am, Ioannis Vranos <woojn...@huskies.com> wrote:
> Nobody wrote:

> > On Tue, 17 Nov 2009 21:39:30 -0800, Keith Thompson wrote:
>
> >>> 10. Use of malloc without casting is considered a poor practice (it is
> >>> an error in C++). Cast it to suitable type instead.
>
> >> No, casting the result of malloc is considered poor practice in C.
> >> This is covered in the comp.lang.c FAQ, <http://www.c-faq.com>.
>
> > Considered by whom?
>
> > I've heard reasonable arguments both for and against. OTOH, I've never
> > seen evidence (e.g. a survey) that either approach could be considered a
> > consensus viewpoint.
>
> Since the casting is not needed, using it is a bad style. At least, it shows
> that there is luck of C knowledge.

Programming is difficult enough when properly done, which is why it's
so seldom properly done; most people here cannot code extempore to the
extent that if anyone does, he is exposed to the vilest kind of
personal abuse for months, an abuse based on envy.

But to make a programmer code to show off a knowledge of what Kenny
and I call the shibboleth, to code defensively in the event that some
Fat Bastard like Heathfield might shit all over you in a way that your
employer can see...that is obscene.

Using malloc with a cast may show a lack of insider knowledge of a
broken language, but it shows purity of heart and competence instead.
I'll take the latter.
>
> --
> Ioannis Vranos
>
> C95 / C++03 Software Developer
>
> http://www.cpp-software.net

spinoza1111

unread,
Nov 19, 2009, 12:51:13 AM11/19/09
to
On Nov 19, 1:23 am, Ioannis Vranos <woojn...@huskies.com> wrote:

> Ioannis Vranos wrote:
>
> > Since the casting is not needed, using it is a bad style. At least, it
>
>   shows that there is lack of C knowledge.

(Sigh) Right, welcome to hell, you'll feel right at home. Sit over
there, between Fat Bastard and Scott Evil. Watch out for Mini-Me, he's
an ankle biter.

spinoza1111

unread,
Nov 19, 2009, 12:52:49 AM11/19/09
to
On Nov 19, 1:25 am, Ioannis Vranos <woojn...@huskies.com> wrote:
> Richard wrote:
> > Ioannis Vranos <woojn...@huskies.com> writes:

>
> >> Michael Tsang wrote:
>
> >>> 10. Use of malloc without casting is considered a poor practice (it is
> >>> an error in C++). Cast it to suitable type instead.
>
> >> C and C++ are different languages.
>
> > And you posted that why?
>
> Because you said we should cast in C, because using malloc() needs a casting
> in C++, where using malloc() is considered poor practice.

Oops. I think you meant "with a cast", and, you're wrong anyway. You
write better than most of the "native" English speakers here but you
need to proofread your copy more carefully.

spinoza1111

unread,
Nov 19, 2009, 12:56:29 AM11/19/09
to
On Nov 19, 1:29 am, Nobody <nob...@nowhere.com> wrote:

> On Wed, 18 Nov 2009 16:42:53 +0000, Richard Tobin wrote:
> >>Sounds to me idiotic not to cast. Strong typing better than weak
> >>typing.
>
> > Casting is a way to defeat strong typing.
>
> >    int a;
> >    char *p;
> >    ...
> >    p = a;
>
> > This is an error requiring a diagnostic.
>
> But we were discussing casting a "void*", which is C's own opt-out of
> static typing.
>
> C doesn't care about either implicit or explicit casts of void* to other

Whenever a programmer starts talking about an object such as a piece
of hardware "caring" about something I know he's incompetent. And when
he starts talking about an idea "caring" about something I know that
he's barking mad, even though he might be in a group where this is
perfectly acceptable, since workgroups, companies, organizations and
whole societies can be in my opinion barking mad: cf. Dianne Vaughan's
"The Challenger Launch Decision" U of C press 1999 and Colin Powell's
UN speech of March 2003 on Saddam Husayn's supposed WMDs on this
matter.

> pointers. An explicit cast at least provides a visual cue as to the
> intent, and will even produce a diagnostic if you explicitly cast to the
> wrong type, e.g.:
>
>         struct foo *p;
>         struct bar *q;
>         void *x;
>
>         p = x;                  /* no diagnostic */
>         p = (struct bar *) x;   /* diagnostic */

It is loading more messages.
0 new messages