C99 Question

  • Thread starter Vijay Kumar R Zanvar
  • Start date
M

Martin Ambuhl

lallous said:
Hello,


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

no_name

lallous said:
Hello,


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
 
K

Kevin Goodsell

no_name said:
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
 
K

Keith Thompson

Servé Lau said:
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)
 
K

Keith Thompson

lallous said:
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.
 
L

Lorenzo Villari

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

Sidney Cadot

no_name said:
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
 
R

Randy Howard

no_name said:
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.
 
S

Sidney Cadot

Randy said:
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
 
C

CBFalconer

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

Randy Howard

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

E. Robert Tisdale

Vijay said:
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.
 
R

Richard Heathfield

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

Sidney Cadot

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
 
R

Richard Bos

CBFalconer said:
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
 
R

Richard Bos

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

Richard Bos

Richard Heathfield said:
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
 
A

Alexander Bartolich

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

Martin Dickopp

Alexander Bartolich said:
begin followup to Richard Bos:

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
 
M

Martin Dickopp

Martin Dickopp said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top