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

后端 未结 3 1291
臣服心动
臣服心动 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:31

    It is convenient, because you can convert this:

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

    Into this:

    #define MALLOC(ptr)   (ptr) = malloc(sizeof(*(ptr) ))
    
    struct node *p;
    MALLOC(p);
    

    Or, for an array:

    #define MALLOC_ARR(ptr, arrsize) \
           (ptr) = malloc(sizeof(*(ptr) ) * arrsize)
    
    struct node *p;
    MALLOC_ARR(p, 20);
    

    And why is this safe? Because the user who uses these macros would be less likely to make mistakes which were outlined by AndreyT, just as in the case of DIM() to get the size of a static array.

    #define DIM(arr)   ((sizeof(arr))/(sizeof(arr[0])))
    

    This is also safer, because the user does not need to make the static array size consistent in several places. Set the array size in one place and then just use the DIM() and you're done! The compiler takes care of it for you.

提交回复
热议问题