Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

malloc

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.

like image 799
Yu Hao Avatar asked Jun 23 '13 07:06

Yu Hao


People also ask

Why use sizeof in malloc?

The sizeof command in C returns the size, in bytes, of any type. The code could just as easily have said malloc(4), since sizeof(int) equals 4 bytes on most machines. Using sizeof, however, makes the code much more portable and readable. The malloc function returns a pointer to the allocated block.

Can you use sizeof with malloc?

Since malloc does not know what type of pointer you want, it returns a pointer to void, in other words a pointer to an unknown type of data. The typical way that you use malloc is with a built-in operator called sizeof(). sizeof() returns the size in bytes of a specific type, which is provided as a parameter.

Is sizeof safe C?

Short answer: yes, it's safe.

Why do we use int * In malloc?

malloc(sizeof(int*)) means you are allocating space off the heap to store a pointer to an int . You are reserving as many bytes as a pointer requires. This returns a value you should cast to an int ** . (A pointer to a pointer to an int .)


1 Answers

It is safer because you don't have to mention the type name twice and don't have to build the proper spelling for the "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 to 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.

like image 75
AnT Avatar answered Sep 18 '22 21:09

AnT