Casting malloc (was: Reading a string of unknown size)



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>


.