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.
Consider the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #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 */
} |
An implementation may add padding to a gadget or widget so that sizeof(gadget) equals sizeof(widget), but this is highly unlikely. More likely, sizeof(gadget) is less than sizeof(widget). In that case
p = malloc(sizeof(gadget)); /* imminent problem */
quietly assigns p to point to storage too small for a widget. The subsequent assignments to p->i and p->d will most likely produce memory overruns.
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().
In this code example, malloc() allocates space for a gadget and the cast immediately converts the returned pointer to a gadget *:
1 2 3 4 5
| widget *p;
/* ... */
p = (gadget *)malloc(sizeof(gadget)); /* invalid assignment */ |
This lets the compiler detect the invalid assignment because it attempts to convert a gadget * into a widget *.
Partager