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

后端 未结 3 1280
臣服心动
臣服心动 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.

    0 讨论(0)
  • 2020-11-22 08:30

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题