c - Why is it safer to use sizeof(*pointer) in malloc -
given
struct node { int a; struct node * next; };
to malloc new structure,
struct node *p = malloc(sizeof(*p));
is safer than
struct node *p = malloc(sizeof(struct node));
why? thought same.
it safer becuse don't have mention type name twice , don't have build proper spelling "dereferenced" version of type. example, don't have "count stars" in
int *****p = malloc(100 * sizeof *p);
compare type-based sizeof
in
int *****p = malloc(100 * sizeof(int ****));
where have make sure used right number of *
under sizeof
.
in order switch type have change 1 place (the declaration of p
) instead of two. , people have habit of casting result of malloc
have change 3 places.
more generally, makes lot of sense stick following guideline: type names belong in declarations , else. actual statements should type-independent. should avoid mentioning type names or using other type-specific features as possible.
the latter means: avoid unnecessary casts. avoid unnecessary type-specific constant syntax (like 0.0
or 0l
plain 0
suffice). avoid mentioning type names under sizeof
. , on.
Comments
Post a Comment