Interview Questions

Why does some code carefully cast the values returned by malloc to the pointer type being allocated?

C Interview Questions and Answers


(Continued from previous question...)

Why does some code carefully cast the values returned by malloc to the pointer type being allocated?

Before ANSI/ISO Standard C introduced the void * generic pointer type, these casts were typically required to silence warnings (and perhaps induce conversions) when assigning between incompatible pointer types.
Under ANSI/ISO Standard C, these casts are no longer necessary. It can also be argued that they are now to be discouraged;Furthermore, well-defined, low-risk implicit conversions (such as those which C has always performed between integer and floating-point types) can be considered a feature.
On the other hand, some programmers prefer to make every conversion explicit, to record that they have considered each case and decided exactly what should happen Also, the casts are typically seen in C code which for one reason or another is intended to be compatible with C++, where explicit casts from void * are required.
(By the way, the language in sections 6.5 and 7.8.5 of K&R2 which suggests that the casts are required is ``overenthusiastic.'')
To some extent, whether you use these casts or not is a matter of style;

(Continued on next question...)

Other Interview Questions