Casting malloc (was: Reading a string of unknown size)
- From: CBFalconer <cbfalconer@xxxxxxxxx>
- Date: Tue, 28 Nov 2006 10:55:28 -0500
websnarf@xxxxxxxxx wrote:
.... snip ...
The cast allows for much more serious type checking. If you are
using the pattern:
<var> = (<type> *) malloc (<count> * sizeof (<type>));
and find a way of enforcing that the exact type is repeated
precisely (i.e., use a macro) then this usually works out better.
If you change <type> or the type of <var> the compiler will issue
a warning unless they are synchronized -- if you leave off this
cast, you get no assistance from the compiler, and you just have
to get it correct.
If you use the recommended:
<var> = malloc(<count> * sizeof *<var>);
you need no casts, and the exact type is enforced without any
concealment behind obfuscating macros or whatever.
--
Chuck F (cbfalconer at maineline dot net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.net>
.
- Follow-Ups:
- Re: Casting malloc (was: Reading a string of unknown size)
- From: websnarf
- Re: Casting malloc (was: Reading a string of unknown size)
- References:
- Re: Reading a string of unknown size
- From: Santosh
- Re: Reading a string of unknown size
- From: santosh
- Re: Reading a string of unknown size
- From: Sundar
- Re: Reading a string of unknown size
- From: websnarf
- Re: Reading a string of unknown size
- Prev by Date: Re: Sharing static variables or function between source files.
- Next by Date: Re: Sharing static variables or function between source files.
- Previous by thread: Re: Reading a string of unknown size
- Next by thread: Re: Casting malloc (was: Reading a string of unknown size)
- Index(es):