Re: C or C++ for FOSS/linux?
- From: jt@xxxxxxxxxxx (Jens Thoms Toerring)
- Date: 29 Dec 2006 22:35:22 GMT
Hadron <hadronquark@xxxxxxxxx> wrote:
"Chris F.A. Johnson" <cfajohnson@xxxxxxxxx> writes:
On 2006-12-29, Sebastian 'lunar' Wiesner wrote:
Jan Panteltje <pNaonStpealmtje@xxxxxxxxx> typed[snip]
int *i = (int *) malloc (100*sizeof(int));
I don't know much of C programming, but that is known to me as the way
you allocate an array of 100 integers on the heap in C.
Wrong; it's:
int *i = malloc (100*sizeof(int));
Even better, make that
int *i = malloc( 100 * sizeof *i );
to avoid two changes if you need to change the type of 'i', one of
wich you can easily forget;-)
You should not cast the value returned by malloc; that can mask
errors.
I have heard this before : but what errors can it mask?
Casting the return value of malloc() keeps the compiler from
complaining if you forgot to include <stdlib.h> where the
prototype for malloc() is. That, in turn, will force the
compiler to assume that malloc() returns an int and convert
the return value to an int before casting it back, as requested
by the explicit cast, to a pointer. This normally isn't an
obvious problem on architectures where an int has the same size
as a pointer and where data and addresses get returned via the
same registers (like i368) but on other architectures this can
lead to strange and hard to find bugs...
Casting the return value of malloc() is only necessary if you
compile with a C++ compiler - it isn't allowed to do it auto-
matically.
Regards, Jens
--
\ Jens Thoms Toerring ___ jt@xxxxxxxxxxx
\__________________________ http://toerring.de
.
- References:
- C or C++ for FOSS/linux?
- From: Beowulf
- Re: C or C++ for FOSS/linux?
- From: Jan Panteltje
- Re: C or C++ for FOSS/linux?
- From: Sebastian 'lunar' Wiesner
- Re: C or C++ for FOSS/linux?
- From: Jan Panteltje
- Re: C or C++ for FOSS/linux?
- From: Sebastian 'lunar' Wiesner
- Re: C or C++ for FOSS/linux?
- From: Jan Panteltje
- Re: C or C++ for FOSS/linux?
- From: Sebastian 'lunar' Wiesner
- Re: C or C++ for FOSS/linux?
- From: Chris F.A. Johnson
- Re: C or C++ for FOSS/linux?
- From: Hadron
- C or C++ for FOSS/linux?
- Prev by Date: Building enterprise websites with apache
- Next by Date: Re: C or C++ for FOSS/linux?
- Previous by thread: Re: C or C++ for FOSS/linux?
- Next by thread: Re: C or C++ for FOSS/linux?
- Index(es):
Relevant Pages
|