Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Casting the result of malloc() to the appropriate pointer type enables the compiler to catch subsequent inadvertent pointer conversions. When allocating individual objects, the "appropriate pointer type" is a pointer to the type argument in the sizeof expression passed to malloc(), as in. This approach is applied in the following code example:

#ccccff
Code Block
Code Block
bgColor
widget *p;

/* ... */

p = (gadget *)malloc(sizeof(gadget)); /* invalid assignment */

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 *. The problem can now be easily identified and corrected:

Code Block
bgColor#ccccff

widget *p;

/* ... */

p = (widget *)malloc(sizeof(widget)); /* invalid assignment */

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

...