Versions Compared

Key

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

...

The argument to malloc() can be any value of (unsigned) type size_t. If the program uses the allocated storage to represent an object (possibly an array) whose size is greater than the requested size, the behavior is undefined. The implicit pointer conversion lets this slip by without complaint from the compiler.

For example:

Code Block
bgColor#ffcccc
#include <stdlib.h>

typedef struct gadget gadget;
struct gadget {
  int i;
  double d;
};

typedef struct widget widget;
struct widget {
  char c[10];
  int i;
  double d;
};

widget *p;

/* ... */

p = malloc(sizeof(gadget)); /* imminent problem */
if (p != NULL) {
  p->i = 0;               /* undefined behavior */
  p->d = 0.0;             /* undefined behavior */
}

...

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

...

Wiki Markup
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3, "Memory management functions"
\[[Summit 05|AA. C References#Summit 05]\] [Question 7.7|http://c-faq.com/malloc/cast.html], and [Question 7.7b|http://c-faq.com/malloc/mallocnocast.html]

...