473,385 Members | 1,309 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

C99 Question

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
110 4355
"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
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
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
"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
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
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
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
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
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
"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
"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
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

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

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

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

Similar topics

1
by: Mohammed Mazid | last post by:
Can anyone please help me on how to move to the next and previous question? Here is a snippet of my code: Private Sub cmdNext_Click() End Sub Private Sub cmdPrevious_Click() showrecord
3
by: Stevey | last post by:
I have the following XML file... <?xml version="1.0"?> <animals> <animal> <name>Tiger</name> <questions> <question index="0">true</question> <question index="1">true</question> </questions>
7
by: nospam | last post by:
Ok, 3rd or is it the 4th time I have asked this question on Partial Types, so, since it seems to me that Partial Types is still in the design or development stages at Microsoft, I am going to ask...
3
by: Ekqvist Marko | last post by:
Hi, I have one Access database table including questions and answers. Now I need to give answer id automatically to questionID column. But I don't know how it is best (fastest) to do? table...
10
by: glenn | last post by:
I am use to programming in php and the way session and post vars are past from fields on one page through to the post page automatically where I can get to their values easily to write to a...
10
by: Rider | last post by:
Hi, simple(?) question about asp.net configuration.. I've installed ASP.NET 2.0 QuickStart Sample successfully. But, When I'm first start application the follow message shown. ========= Server...
53
by: Jeff | last post by:
In the function below, can size ever be 0 (zero)? char *clc_strdup(const char * CLC_RESTRICT s) { size_t size; char *p; clc_assert_not_null(clc_strdup, s); size = strlen(s) + 1;
56
by: spibou | last post by:
In the statement "a *= expression" is expression assumed to be parenthesized ? For example if I write "a *= b+c" is this the same as "a = a * (b+c)" or "a = a * b+c" ?
2
by: Allan Ebdrup | last post by:
Hi, I'm trying to render a Matrix question in my ASP.Net 2.0 page, A matrix question is a question where you have several options that can all be rated according to several possible ratings (from...
3
by: Zhang Weiwu | last post by:
Hello! I wrote this: ..required-question p:after { content: "*"; } Corresponding HTML: <div class="required-question"><p>Question Text</p><input /></div> <div...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.