...
Here, malloc()
allocates space for a gadget
and the cast immediately converts the returned pointer to a gadget *
. This lets the compiler detect the invalid assignment, because it attempts to convert a gadget *
into a widget *
.
Compliant Solution
Repeating the same type in the sizeof
expression and the pointer cast is easy to do, but still invites errors. Packaging the repetition in a macro, such as:
...
Here, the entire allocation expression (to the right of the assignment operator) allocates storage for a widget
and returns a widget *
. If p were not a {{widget *
, the compiler would complain about the assignment.
...
When allocating an array with N
elements of type T
, the appropriate type in the cast expression is still T *
, but the argument to malloc()
should be of the form N * sizeof(T)
. Again, packaging this form as a macro, such as:
...