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

后端 未结 3 1351
臣服心动
臣服心动 2020-11-22 07:40

Given

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

To malloc a new structure,

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


        
3条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 08:26

    Because if at some later point in time p is made to point to another structure type then your memory allocation statement using malloc doesn't have to change, it still allocates enough memory required for the new type. It ensures:

    • You don't have to modify the memory allocation statement every time you change the type it allocates memory for.
    • Your code is more robust and less prone to manual errors.

    In general it is always a good practice to not rely on concrete types and the the first form just does that ,it doesn't hard code a type.

提交回复
热议问题