Why is it safer to use sizeof(*pointer) in malloc

Yu Hao picture Yu Hao · Jun 23, 2013 · Viewed 29.8k times · Source

Given

struct node
{
     int a;
     struct node * next;
};

To malloc a new structure,

struct node *p = malloc(sizeof(*p));

is safer than

struct node *p = malloc(sizeof(struct node));

Why? I thought they are the same.

Answer

AnT picture AnT · Jun 23, 2013

It is safer becuse you don't have to mention the type name twice and don't have to build the proper spelling for "dereferenced" version of the type. For example, you don't have to "count the stars" in

int *****p = malloc(100 * sizeof *p);

Compare that to the type-based sizeof in

int *****p = malloc(100 * sizeof(int ****));

where you have too make sure you used the right number of * under sizeof.

In order to switch to another type you only have to change one place (the declaration of p) instead of two. And people who have the habit of casting the result of malloc have to change three places.

More generally, it makes a lot of sense to stick to the following guideline: type names belong in declarations and nowhere else. The actual statements should be type-independent. They should avoid mentioning any type names or using any other type-specific features as much as possible.

The latter means: Avoid unnecessary casts. Avoid unnecessary type-specific constant syntax (like 0.0 or 0L where a plain 0 would suffice). Avoid mentioning type names under sizeof. And so on.