By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,421 Members | 1,128 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,421 IT Pros & Developers. It's quick & easy.

C99 Question

P: n/a
Hi,

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

Thanks.

--
Vijay Kumar R Zanvar
My Home Page - http://www.geocities.com/vijoeyz/
Nov 14 '05 #1
Share this Question
Share on Google+
110 Replies


P: n/a
"Vijay Kumar R Zanvar" <vi*****@hotpop.com> writes:
Which section of C99 says that return value
of malloc(3) should not be casted?


None. The standard only defines the language, it does not advise on
good programming style.

Martin
Nov 14 '05 #2

P: n/a
Vijay Kumar R Zanvar wrote:
Hi,

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


The same section that says you should not microwave your cat.

Casting malloc is deprecated by the regular subscribers in this newsgroup
because:

(a) it does nothing good;
(b) it doesn't stop anything bad happening;
(c) it can (in certain circumstances in C90) actually /cause/ something bad
to happen.

Even if you're not persuaded by (a) and (b) together (which you probably
should be), (c) should be a showstopper.

The malloc function - Just Don't Cast.

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #3

P: n/a
Hello,
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
Vijay Kumar R Zanvar wrote:
The malloc function - Just Don't Cast. This might be silly from me, but you mean don't cast as:
int *i = (int *) malloc(sizeof(int));
?
What other solutions are there then? just assign w/o casting?

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton

Nov 14 '05 #4

P: n/a
"Vijay Kumar R Zanvar" <vi*****@hotpop.com> wrote:
Which section of C99 says that return value
of malloc(3) should not be casted?


There is no section of C99 that says that; if there were, you wouldn't
be able to do it. It's a very bad idea all the same.
In fact, it's similar to there not being any law forbidding you to shoot
yourself in the foot. You _are_ allowed to do that; but expect it to
hurt, and do not expect your insurance to pay for the medical costs.

Richard
Nov 14 '05 #5

P: n/a
lallous wrote:
Hello,
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
Vijay Kumar R Zanvar wrote:
The malloc function - Just Don't Cast. This might be silly from me, but you mean don't cast as:
int *i = (int *) malloc(sizeof(int));
?


Yes, I mean that this cast is pointless and can be harmful.
What other solutions are there then? just assign w/o casting?


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

works for any object type T. You can omit n if it's 1, of course.

Your example would be better written as: int *i = malloc(sizeof *i);

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #6

P: n/a
Vijay Kumar R Zanvar wrote:

Hi,

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


How about an errata from K&R2 instead ?

142(§6.5, toward the end):
The remark about casting the return value of malloc
("the proper method is to declare ... then explicitly coerce")
needs to be rewritten. The example is correct and works,
but the advice is debatable in the context of the
1988-1989 ANSI/ISO standards. It's not necessary
(given that coercion of void * to ALMOSTANYTYPE * is automatic),
and possibly harmful if malloc,
or a proxy for it, fails to be declared as returning void *.
The explicit cast can cover up an unintended error.
On the other hand, pre-ANSI, the cast was necessary,
and it is in C++ also.

http://cm.bell-labs.com/cm/cs/cbook/2ediffs.html

--
pete
Nov 14 '05 #7

P: n/a
Richard Heathfield wrote:

lallous wrote:
Hello,
"Richard Heathfield" <in*****@address.co.uk.invalid>
wrote in message
news:3f******@news2.power.net.uk...
Vijay Kumar R Zanvar wrote:
The malloc function - Just Don't Cast.

This might be silly from me, but you mean don't cast as:
int *i = (int *) malloc(sizeof(int));
?


Yes, I mean that this cast is pointless and can be harmful.
What other solutions are there then? just assign w/o casting?


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

works for any object type T. You can omit n if it's 1, of course.

Your example would be better written as: int *i = malloc(sizeof *i);


Neither of your posts in this thread, mention stdlib.h.
In order to write the lines that you wrote, there has to be

#include <stdlib.h>

in the code, somewhere before those lines,
otherwise the compiler will generate a warning which,
(though the warning signifies an absence of stdlib.h to us,)
may suggest a cast, and confuse the programmer into thinking
that the return value of malloc should be cast.
And who's the programmer going to believe, clc or his compiler ?

--
pete
Nov 14 '05 #8

P: n/a
pete wrote:
Richard Heathfield wrote:

<snip>
Your example would be better written as: int *i = malloc(sizeof *i);
Neither of your posts in this thread, mention stdlib.h.


Thanks for mentioning <stdlib.h> which, of course, provides the essential
function prototype that is so critical to correct malloc usage.
And who's the programmer going to believe, clc or his compiler ?


If he is wise, he will believe clc (and then he will find out precisely
*why* his compiler is right).

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #9

P: n/a
Hello,

"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
pete wrote:
Richard Heathfield wrote:

<snip>
Your example would be better written as: int *i = malloc(sizeof *i);
Neither of your posts in this thread, mention stdlib.h.


Thanks for mentioning <stdlib.h> which, of course, provides the essential
function prototype that is so critical to correct malloc usage.
And who's the programmer going to believe, clc or his compiler ?


If he is wise, he will believe clc (and then he will find out precisely
*why* his compiler is right).

I use the cast to avoid warning or when using malloc() in a C++ program.

The stdlib.h would remove the warning? How, compiler switch (like vc's
#pragma warn(disable:n))?

--
Elias --
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton

Nov 14 '05 #10

P: n/a
"lallous" <la*****@lgwm.org> wrote:
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
Thanks for mentioning <stdlib.h> which, of course, provides the essential
function prototype that is so critical to correct malloc usage.
I use the cast to avoid warning or when using malloc() in a C++ program.
- don't use malloc() in a C++ program, use new;
- don't confound C with C++, and least of all good C with good C++;
- therefore, don't apply a C++ hack-around to proper C code.
The stdlib.h would remove the warning? How, compiler switch (like vc's
#pragma warn(disable:n))?


Of course not - by the simple expedient of providing a proper
declaration for malloc() and friends. As all good C code should do for
all used functions.

Richard
Nov 14 '05 #11

P: n/a
"lallous" <la*****@lgwm.org> wrote in message
news:bs***********@ID-161723.news.uni-berlin.de...
I use the cast to avoid warning or when using malloc() in a C++ program.
First, you should use new in a C++ program, and you don't have to cast new.

Second, the whole point is that if you forget to include stdlib.h and you
try to use malloc, the compiler lets malloc return int instead of void *. If
you don't cast the return value, the compiler should give an error that
there is no automatic conversion from int to pointer type. If you do cast
the return value, the compiler thinks you are saying "shut up, I know what
I'm doing" and will happily generate some code that converts an int to a
pointer. This causes big problemos on platforms where sizeof(int) != sizeof
(void *) and 64 bit platforms are coming pretty soon.
The stdlib.h would remove the warning? How, compiler switch (like vc's
#pragma warn(disable:n))?


Do not remove the warning, write correct code.
Nov 14 '05 #12

P: n/a
lallous wrote:

Hello,

"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
pete wrote:
Richard Heathfield wrote:
>
<snip>
> Your example would be better written as: int *i = malloc(sizeof *i);

Neither of your posts in this thread, mention stdlib.h.


Thanks for mentioning <stdlib.h> which, of course, provides the essential
function prototype that is so critical to correct malloc usage.
And who's the programmer going to believe, clc or his compiler ?


If he is wise, he will believe clc
(and then he will find out precisely *why* his compiler is right).


I use the cast to avoid warning or when using
malloc() in a C++ program.


The rumors are, that well written C++ programs
which look like C++ programs, don't use malloc.
The stdlib.h would remove the warning? How, compiler switch (like vc's
#pragma warn(disable:n))?


You need to understand the reason for the warning.

malloc returns type void*. The prototype for malloc is in stdlib.h.
If a function, like malloc, doesn't have a prototype in scope,
then the compiler will assume that the function returns type int.
If you assign an int to a pointer, you get a warning or an error.

If stdlib.h is #included, then the compiler will know that
malloc returns type void*. When you assign a void* value
to any type of pointer to an object, there is no problem, no warning.

--
pete
Nov 14 '05 #13

P: n/a

"pete" <pf*****@mindspring.com> wrote in message
news:3F**********@mindspring.com...
lallous wrote:

Hello,

"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
pete wrote:

> Richard Heathfield wrote:
>>

<snip>

>> Your example would be better written as: int *i = malloc(sizeof *i); >
> Neither of your posts in this thread, mention stdlib.h.

Thanks for mentioning <stdlib.h> which, of course, provides the essential function prototype that is so critical to correct malloc usage.

> And who's the programmer going to believe, clc or his compiler ?

If he is wise, he will believe clc
(and then he will find out precisely *why* his compiler is right).
I use the cast to avoid warning or when using
malloc() in a C++ program.


The rumors are, that well written C++ programs
which look like C++ programs, don't use malloc.
The stdlib.h would remove the warning? How, compiler switch (like vc's
#pragma warn(disable:n))?


You need to understand the reason for the warning.

malloc returns type void*. The prototype for malloc is in stdlib.h.
If a function, like malloc, doesn't have a prototype in scope,
then the compiler will assume that the function returns type int.

Yes, I know that.
If you assign an int to a pointer, you get a warning or an error.

If stdlib.h is #included, then the compiler will know that
malloc returns type void*. When you assign a void* value
to any type of pointer to an object, there is no problem, no warning. I know that C++ uses new, however C++ enforces type casting and that is why
I cast return value of malloc() to the desired type. C would access to
convert void* to any other pointer.

Anyway, thank you all for the info.
Elias
--
pete

Nov 14 '05 #14

P: n/a
lallous wrote:

"pete" <pf*****@mindspring.com> wrote in message
news:3F**********@mindspring.com...
lallous wrote:

Hello,

"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
> pete wrote:
>
> > Richard Heathfield wrote:
> >>
>
> <snip>
>
> >> Your example would be better written as: int *i = malloc(sizeof *i); > >
> > Neither of your posts in this thread, mention stdlib.h.
>
> Thanks for mentioning <stdlib.h> which, of course, provides the essential > function prototype that is so critical to correct malloc usage.
>
> > And who's the programmer going to believe, clc or his compiler ?
>
> If he is wise, he will believe clc
> (and then he will find out precisely *why* his compiler is right).

I use the cast to avoid warning or when using
malloc() in a C++ program.


The rumors are, that well written C++ programs
which look like C++ programs, don't use malloc.
The stdlib.h would remove the warning? How, compiler switch (like vc's
#pragma warn(disable:n))?


You need to understand the reason for the warning.

malloc returns type void*. The prototype for malloc is in stdlib.h.
If a function, like malloc, doesn't have a prototype in scope,
then the compiler will assume that the function returns type int.

Yes, I know that.
If you assign an int to a pointer, you get a warning or an error.

If stdlib.h is #included, then the compiler will know that
malloc returns type void*. When you assign a void* value
to any type of pointer to an object, there is no problem,
no warning.

I know that C++ uses new, however C++ enforces type
casting and that is why
I cast return value of malloc() to the desired type. C would access to
convert void* to any other pointer.

Anyway, thank you all for the info.


And so, to sum up, the big advantage of not casting,
is that the warning will alert the programmer if the code
has changed in some way such that the prototype for malloc
is no longer in scope,
which is something that really does happen in real programs.

Not having the prototype in scope, gives your code undefined behavior,
which means that it might work right in your tests
and still have problems in the field.

--
pete
Nov 14 '05 #15

P: n/a
lallous wrote:
.... snip ...
I use the cast to avoid warning or when using malloc() in a C++
program.


This is c.l.c. c.l.c++ is another newsgroup, dealing with another
(some say inferior) language, named C++, which is distinct from C.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #16

P: n/a
pete <pf*****@mindspring.com> wrote:
And so, to sum up, the big advantage of not casting,
is that the warning will alert the programmer if the code
has changed in some way such that the prototype for malloc
is no longer in scope,


No. The _big_ advantage of not casting malloc() is that you have several
fewer useless casts in your program, just as the big advantage of not
hanging a high voltage sign on batteries is that you're not carrying
several high voltage signs for your mobile phone et cetera.
Both also have other advantages (you will be warned if you forget
<stdlib.h>; you won't be hampered when you try to use your phone), but
the main advantage is that the fewer useless warning signals, the more
attention you will pay if you really _are_ doing something awkward
involving pointers - or if you really are in danger of being
electrocuted.

Richard
Nov 14 '05 #17

P: n/a
Richard Bos wrote:
pete <pf*****@mindspring.com> wrote:
And so, to sum up, the big advantage of not casting,
is that the warning will alert the programmer if the code
has changed in some way such that the prototype for malloc
is no longer in scope,


No. The _big_ advantage of not casting malloc() is that you have
several fewer useless casts in your program, just as the big
advantage of not hanging a high voltage sign on batteries is that
you're not carrying several high voltage signs for your mobile
phone et cetera. Both also have other advantages (you will be
warned if you forget <stdlib.h>; you won't be hampered when you
try to use your phone), but the main advantage is that the fewer
useless warning signals, the more attention you will pay if you
really _are_ doing something awkward involving pointers - or if
you really are in danger of being electrocuted.


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

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!
Nov 14 '05 #18

P: n/a
Vijay Kumar R Zanvar wrote:
Hi,

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


None. This is a question of good programming practice, not of language
legislation.
--
Martin Ambuhl

Nov 14 '05 #19

P: n/a
lallous wrote:
Hello,
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
Vijay Kumar R Zanvar wrote:
The malloc function - Just Don't Cast.


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


Of course you don't use a cast there. It is so simple to find other
solutions that it is hard to believe this is an honest question.

int *i = malloc(sizeof(int));
or [better]
int *i = malloc(sizeof *i);

And check that i is not NULL.

--
Martin Ambuhl

Nov 14 '05 #20

P: n/a
On Tue, 30 Dec 2003 19:07:47 GMT, Martin Ambuhl
<ma*****@earthlink.net> wrote:
lallous wrote:
Hello,
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
Vijay Kumar R Zanvar wrote:
The malloc function - Just Don't Cast.


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


Of course you don't use a cast there. It is so simple to find other
solutions that it is hard to believe this is an honest question.

int *i = malloc(sizeof(int));
or [better]
int *i = malloc(sizeof *i);

And check that i is not NULL.


Che noia .....
Ci stai a *movimentare* la situazione e fare una bella *gara*
aperta a tutti i partecipanti di questo NG:
qualcuno proponga un bel problema (e lo posti a una data ora di un
dato giorno (domani)) da risolvere usando lo standard C.
(mi raccomando *non* sia qualcosa risolvibile solo con *trucchi vari*)

Si decida di dare 24 ore e dopo 24 ore ognuno posti la sua soluzione
(tutti in contemporanea). Così vediamo chi è più bravo e vedremo se
i bla bla bla parolai sono meglio di quelli che scrivono esempi con il
codice in C che abbia *almeno* un qualche loop.

Per quel che mi riguarda io non sono un bravo programmatore (non sono
un professionista faccio altro nella vita; penso che altri faranno
bene) ma visto che ho sentito dire "scemo" e criticate a destra e a
sinistra vorrei almeno **vedere** quanto siete bravi e intelligenti.

Ho poco tempo e tra qualche giorno dovrò andare a lavorare lontano da
casa: se ci state sbrigatevi.
Ciao Ciao
Nov 14 '05 #21

P: n/a
no_name wrote:

Che noia .....


No offense, but this is an English group. Posts in other languages are
considered inappropriate. I believe there is an Italian equivalent
somewhere - it.comp.lang.c or something like that.

(...This *is* Italian, isn't it? At first I thought it was French for
some reason.)

-Kevin
--
My email address is valid, but changes periodically.
To contact me please use the address from a recent posting.
Nov 14 '05 #22

P: n/a
"Servé Lau" <i@bleat.nospam.com> writes:
"lallous" <la*****@lgwm.org> wrote in message
news:bs***********@ID-161723.news.uni-berlin.de...
I use the cast to avoid warning or when using malloc() in a C++ program.


First, you should use new in a C++ program, and you don't have to cast new.

Second, the whole point is that if you forget to include stdlib.h and you
try to use malloc, the compiler lets malloc return int instead of void *. If
you don't cast the return value, the compiler should give an error that
there is no automatic conversion from int to pointer type. If you do cast
the return value, the compiler thinks you are saying "shut up, I know what
I'm doing" and will happily generate some code that converts an int to a
pointer. This causes big problemos on platforms where sizeof(int) != sizeof
(void *) and 64 bit platforms are coming pretty soon.


Strictly speaking, the problem is that the compiler *doesn't* generate
code that converts an int to a pointer. It generates code that calls
the function and just assumes (because you told it to) that the result
is already an int. The pointer value that the function actually
returns may not even be in the same place that the calling code looks
for the int it expects (for example, it could be in a different
register).

"If you lie to the compiler, it will get its revenge." (credited to
Henry Spencer)

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #23

P: n/a
"lallous" <la*****@lgwm.org> writes:
[...]
I know that C++ uses new, however C++ enforces type casting and that is why
I cast return value of malloc() to the desired type. C would access to
convert void* to any other pointer.


If you want to write C, use malloc() and don't cast the result.
<OT>If you want to write C++, use new, not malloc().</OT>

If you want to write C that your C++ compiler won't complain about,
you're probably going to a lot of trouble for no good reason. If you
actually have a good reason, I'd be interested in knowing what it is;
perhaps we can help you find an alternative.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://www.sdsc.edu/~kst>
Schroedinger does Shakespeare: "To be *and* not to be"
(Note new e-mail address)
Nov 14 '05 #24

P: n/a

"> Per quel che mi riguarda io non sono un bravo programmatore (non sono
un professionista faccio altro nella vita; penso che altri faranno
bene) ma visto che ho sentito dire "scemo" e criticate a destra e a
sinistra vorrei almeno **vedere** quanto siete bravi e intelligenti


You must be kidding I hope...
I think they don't have to give you any proof that they're good programmers,
if you lurk here like I do, you surely know how good they are here...

Nov 14 '05 #25

P: n/a
no_name wrote:
[snip] Che noia .....
Ci stai a *movimentare* la situazione e fare una bella *gara*
aperta a tutti i partecipanti di questo NG:
qualcuno proponga un bel problema (e lo posti a una data ora di un
dato giorno (domani)) da risolvere usando lo standard C.
(mi raccomando *non* sia qualcosa risolvibile solo con *trucchi vari*)


We kunnen met aan zekerheid grenzende waarschijnlijkheid stellen dat de
overgrote meerderheid van de lezers alhier niet in staat is om berichten
te lezen in een andere taal dan het Engels. Het verdient om die reden
wellicht de aanbeveling om zulks niet te proberen.

Laat mij verder de gelegenheid waarnemen om op te merken dat ik van
mening ben dat (binnen het kader van de programmeertaal C) het expliciet
omvormen van het type (middels een 'mal' operatie), in het geval van
resultaten verkregen uit functies die geheugen van de zgn. 'hoop'
reserveren welke binnen de standaard-bibliotheek worden aangeboden, niet
zo'n doodzonde is als binnen deze gemeenschap menigmaal is gesuggereerd.

Met vriendelijke groet,

Sidney

Nov 14 '05 #26

P: n/a
In article <bs**********@news.tudelft.nl>, si****@jigsaw.nl says...
no_name wrote:
[snip]

Che noia .....
Ci stai a *movimentare* la situazione e fare una bella *gara*
aperta a tutti i partecipanti di questo NG:
qualcuno proponga un bel problema (e lo posti a una data ora di un
dato giorno (domani)) da risolvere usando lo standard C.
(mi raccomando *non* sia qualcosa risolvibile solo con *trucchi vari*)


We kunnen met aan zekerheid grenzende waarschijnlijkheid stellen dat de
overgrote meerderheid van de lezers alhier niet in staat is om berichten
te lezen in een andere taal dan het Engels. Het verdient om die reden
wellicht de aanbeveling om zulks niet te proberen.

Laat mij verder de gelegenheid waarnemen om op te merken dat ik van
mening ben dat (binnen het kader van de programmeertaal C) het expliciet
omvormen van het type (middels een 'mal' operatie), in het geval van
resultaten verkregen uit functies die geheugen van de zgn. 'hoop'
reserveren welke binnen de standaard-bibliotheek worden aangeboden, niet
zo'n doodzonde is als binnen deze gemeenschap menigmaal is gesuggereerd.


Jr xhaara zrg nna mrxreurvq teramraqr jnnefpuvwayvwxurvq fgryyra qng qr
biretebgr zrreqreurvq ina qr yrmref nyuvre avrg va fgnng vf bz orevpugra
gr yrmra va rra naqrer gnny qna urg Ratryf. Urg ireqvrag bz qvr erqra
jryyvpug qr nnaoriryvat bz mhyxf avrg gr ceborera.

Ynng zvw ireqre qr tryrtraurvq jnnearzra bz bc gr zrexra qng vx ina
zravat ora qng (ovaara urg xnqre ina qr cebtenzzrregnny P) urg rkcyvpvrg
bzibezra ina urg glcr (zvqqryf rra 'zny' bcrengvr), va urg triny ina
erfhygngra irexertra hvg shapgvrf qvr trurhtra ina qr mta. 'ubbc'
erfreirera jryxr ovaara qr fgnaqnneq-ovoyvbgurrx jbeqra nnatrobqra, avrg
mb'a qbbqmbaqr vf nyf ovaara qrmr trzrrafpunc zravtznny vf trfhttrerreq.

--
Randy Howard
2reply remove FOOBAR

Nov 14 '05 #27

P: n/a
Randy Howard wrote:
Jr xhaara zrg nna mrxreurvq teramraqr jnnefpuvwayvwxurvq fgryyra qng qr
[...]


Sorry about my brief relapse into my native tongue (Dutch). Figured out
this would perhaps get the message across to our Italian friend.

Best regards,

Sidney

Nov 14 '05 #28

P: n/a
Sidney Cadot wrote:
Randy Howard wrote:
Jr xhaara zrg nna mrxreurvq teramraqr jnnefpuvwayvwxurvq fgryyra qng qr
> [...]


Sorry about my brief relapse into my native tongue (Dutch). Figured out
this would perhaps get the message across to our Italian friend.


I was going to reply in kind, but discovered that there is no
mechanism to do so (that I can detect) on NS4.75 :-( Reading is
possible, however.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #29

P: n/a
In article <bs**********@news.tudelft.nl>, si****@jigsaw.nl says...
Randy Howard wrote:
Jr xhaara zrg nna mrxreurvq teramraqr jnnefpuvwayvwxurvq fgryyra qng qr
> [...]


Sorry about my brief relapse into my native tongue (Dutch). Figured out
this would perhaps get the message across to our Italian friend.


You may notice that if you rot13 my last message, it seems familiar
somehow.

--
Randy Howard
2reply remove FOOBAR

Nov 14 '05 #30

P: n/a
Vijay Kumar R Zanvar wrote:
Which section of C99 says that
the return value of malloc should not be casted?


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

I *always* cast malloc's return value

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

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

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

Nov 14 '05 #31

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


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

I *always* cast malloc's return value

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

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

char *p = new char[n];

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

There is *no* advantage to omitting the cast.


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

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #32

P: n/a
Randy Howard wrote:
Sorry about my brief relapse into my native tongue (Dutch). Figured out
this would perhaps get the message across to our Italian friend.
You may notice that if you rot13 my last message, it seems familiar
somehow.


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

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

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

Best regards,

Sidney

Nov 14 '05 #33

P: n/a
On Tue, 30 Dec 2003 12:42:42 +0200
"lallous" <la*****@lgwm.org> wrote:
Hello,
"Richard Heathfield" <in*****@address.co.uk.invalid> wrote in message
news:3f******@news2.power.net.uk...
Vijay Kumar R Zanvar wrote:
The malloc function - Just Don't Cast.

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


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

#include <stdlib.h>

/* lots of stuff */

derf = malloc( N * sizeof *derf );

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

If your compiler complains about the above (given appropriate
definitions of derf and N) then you are not invoking it correctly or I
have made a trypo.
--
Flash Gordon
Paid to be a Geek & a Senior Software Developer
Although my email address says spam, it is real and I read it.
Nov 14 '05 #34

P: n/a
CBFalconer <cb********@yahoo.com> wrote:
Richard Bos wrote:
No. The _big_ advantage of not casting malloc() is that you have
several fewer useless casts in your program, just as the big
advantage of not hanging a high voltage sign on batteries is that
you're not carrying several high voltage signs for your mobile
phone et cetera. Both also have other advantages (you will be
warned if you forget <stdlib.h>; you won't be hampered when you
try to use your phone), but the main advantage is that the fewer
useless warning signals, the more attention you will pay if you
really _are_ doing something awkward involving pointers - or if
you really are in danger of being electrocuted.


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


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

Richard
Nov 14 '05 #35

P: n/a
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
I *always* cast malloc's return value

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

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


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

Richard
Nov 14 '05 #36

P: n/a
Richard Heathfield <do******@address.co.uk.invalid> wrote:
E. Robert Tisdale wrote:
There is *no* advantage to omitting the cast.


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


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

Richard
Nov 14 '05 #37

P: n/a
begin followup to Richard Bos:
Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.


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

initialization makes pointer from integer without a cast

is mandatory for a conforming compiler, while

implicit declaration of function `malloc'

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

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

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

--
Für Google, Tux und GPL!
Nov 14 '05 #38

P: n/a
Alexander Bartolich wrote:
begin followup to Richard Bos:
Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.


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

initialization makes pointer from integer without a cast

is mandatory for a conforming compiler, while

implicit declaration of function `malloc'

is not.


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

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

--
Richard Heathfield : bi****@eton.powernet.co.uk
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton
Nov 14 '05 #39

P: n/a
Alexander Bartolich <al*****************@gmx.at> writes:
begin followup to Richard Bos:
Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.
Let's see if I understand this right.
The danger is that the diagnostic

initialization makes pointer from integer without a cast

is mandatory for a conforming compiler,


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

implicit declaration of function `malloc'

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

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

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


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

Martin
Nov 14 '05 #40

P: n/a
Martin Dickopp <ex****************@zero-based.org> writes:
Yes, a conforming compiler is not required to emit a diagnostic if a
function is used without prior declaration.


Please ignore that part of my previous posting. Despite the subject,
I failed to realize that this thread is about C99.

Martin
Nov 14 '05 #41

P: n/a
"E. Robert Tisdale" wrote:
Vijay Kumar R Zanvar wrote:
Which section of C99 says that
the return value of malloc should not be casted?


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

I *always* cast malloc's return value


Mr Zanvar should note that ERT, better known in these parts as
Trollsdale, is usually wrong and gives (as in this case) bad
advice.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #42

P: n/a
In article <3F**************@jpl.nasa.gov>,
"E. Robert Tisdale" <E.**************@jpl.nasa.gov> wrote:
Vijay Kumar R Zanvar wrote:
Which section of C99 says that
the return value of malloc should not be casted?
Good question! The ANSI/ISO C 99 standard does *not* say that the
return value of malloc should not be casted.

I *always* cast malloc's return value

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

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


Pick a language. Either write C or write C++. If you're writing C++,
then use new (and don't cast), if you're writing C, then use malloc (and
don't cast). If, you are writing C, but trying to feed it to a C++
compiler, then why not just write C++, and be through with it?
There is *no* advantage to omitting the cast.
That is simply wrong. If, for instance, you forget to include stdlib.h,
and malloc's prototype is not in scope, a (C89) compiler will assume
that malloc is defined as "int malloc()", which means that the result is
undefined, and you should get some diagnostic from your compiler. Now,
on platforms where sizeof(int) == sizeof(void*), and pointers and
integers are returned in the same way, this *might* be fine, but you
can't count on it.
It is purely a style issue but some C programmers have become fond of
this style and invented various *lame* arguments to justify their
personal aesthetics.


Casting, in this case, does nothing but hide potential errors.

Nov 14 '05 #43

P: n/a
"Martin Dickopp" <ex****************@zero-based.org> wrote in message
news:bs*************@news.t-online.com...
I consider people who compile C code with a C++ compiler to be quite at
the newbie end of the spectrum.


You make me feel young again.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #44

P: n/a
"CBFalconer" <cb********@yahoo.com> wrote in message
news:3F***************@yahoo.com...
"E. Robert Tisdale" wrote:
Vijay Kumar R Zanvar wrote:
Which section of C99 says that
the return value of malloc should not be casted?


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

I *always* cast malloc's return value


Mr Zanvar should note that ERT, better known in these parts as
Trollsdale, is usually wrong and gives (as in this case) bad
advice.


Whatever his record, I happen to agree with him on this matter.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #45

P: n/a
On Wed, 31 Dec 2003 10:52:44 GMT, rl*@hoekstra-uitgeverij.nl (Richard
Bos) wrote in comp.lang.c:
Richard Heathfield <do******@address.co.uk.invalid> wrote:
E. Robert Tisdale wrote:
There is *no* advantage to omitting the cast.


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


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

Richard


The reason that it is not as dangerous in a conforming C99
implementation is that C99 requires a declaration in scope when a
function is called. It is still dangerous if the declaration is not a
prototype, as one could insert the following in one's source file to
shut up the compiler:

void *malloc();

....which is a declaration but not a prototype, causing the compiler to
pass the argument as a signed type, rather than a size_t.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 14 '05 #46

P: n/a
On Wed, 31 Dec 2003 14:19:34 +0000, Richard Heathfield
<in*****@address.co.uk.invalid> wrote in comp.lang.c:
Alexander Bartolich wrote:
begin followup to Richard Bos:
Beg to differ. It _is_ dangerous. Not to the code, but to the
programmer, and even more importantly to the maintainer.


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

initialization makes pointer from integer without a cast

is mandatory for a conforming compiler, while

implicit declaration of function `malloc'

is not.


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

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


Undefined behavior under C99:

void *malloc(); /* an acceptable declaration */

void my_function(void)
{
char *fred = malloc(100);
}

....because the declaration is not a full prototype and the argument
will be passed as a signed int instead of a size_t.

Not too swift to toss in one's own declaration? Agreed. But doing so
to silence the compiler diagnostic is not much different than tossing
in the cast to do the same thing.

Probably depends on which diagnostic a particular C99 implementation
would output for the code without the declaration (missing declaration
or int-to-pointer conversion), or which would be first if it emitted
both.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Nov 14 '05 #47

P: n/a
"P.J. Plauger" wrote:
"CBFalconer" <cb********@yahoo.com> wrote in message
"E. Robert Tisdale" wrote:
Vijay Kumar R Zanvar wrote:

> Which section of C99 says that
> the return value of malloc should not be casted?

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

I *always* cast malloc's return value


Mr Zanvar should note that ERT, better known in these parts as
Trollsdale, is usually wrong and gives (as in this case) bad
advice.


Whatever his record, I happen to agree with him on this matter.


However you have, I believe, a different motive. You want your
shrouded source to be compilable by unwashed idiots on any
compiler without complaint or handholding.

--
Chuck F (cb********@yahoo.com) (cb********@worldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net> USE worldnet address!

Nov 14 '05 #48

P: n/a
"CBFalconer" <cb********@yahoo.com> wrote in message
news:3F***************@yahoo.com...
Mr Zanvar should note that ERT, better known in these parts as
Trollsdale, is usually wrong and gives (as in this case) bad
advice.


Whatever his record, I happen to agree with him on this matter.


However you have, I believe, a different motive. You want your
shrouded source to be compilable by unwashed idiots on any
compiler without complaint or handholding.


Believe what you want.

P.J. Plauger
Dinkumware, Ltd.
http://www.dinkumware.com
Nov 14 '05 #49

P: n/a
CBFalconer <cb********@yahoo.com> writes:
And it also encourages you to treat the presence of ANY cast as an
indication of a potential problem. There are very few places they
are really necessary, with calls to variadic functions heading my
list.


There are several situations where a cast legitimately comes in handy:

* Conversion of one type's range to another's, as in the
argument to the <ctype.h> to*() and is*() functions:
isupper((unsigned char) c)

* Conversion of an integer to a floating-point type for
use in arithmetic. (Sure, you can assign it to a
variable or multiply it by 1.0, but a cast can
sometimes clarify what you're doing.)

* Converting a pointer to the first member of a structure
to a pointer to the structure, or a pointer to a member
of a union to a pointer to the union.

* Converting an lvalue to an rvalue for use in macros
that can be used for access to objects but should not
be used to modify those objects. (The unary plus
operator is an alternative.)

* Casting between different pointer-to-character types
for, e.g., passing a unsigned char array to strcpy().
(You can avoid it by using a void * pointer variable as
an intermediary, but that's hardly an improvement.)

* Silencing compiler warnings about `comparing signed and
unsigned types' ;-(

* Passing a null pointer to a varargs function.

--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv wxyz.\
\n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}
Nov 14 '05 #50

110 Replies

This discussion thread is closed

Replies have been disabled for this discussion.