What is the Best Practice for malloc?

后端 未结 3 2058
南旧
南旧 2020-12-18 04:43

Which if any of the following are correct and would be considered best practice to create a char string capable of holding 100 characters?

char * charStringA         


        
3条回答
  •  余生分开走
    2020-12-18 05:38

    char * charStringA = malloc(100);
    char * charStringB = malloc(sizeof(char)*100);
    

    Both are equally correct.
    Two important points that should be considered in this evaluation are:

    1. size of char is guaranteed to be one byte by the C standard.
    2. A void pointer can be assigned to any pointer without an explicit cast in C and the casting is unnecessary. Casting the return value of malloc is considered as an bad practice because of the following:

    What's wrong with casting malloc's return value?


    The above answer applies to the options mentioned in the OP. An better practice is to use sizeof without making any assumptions about the size of any type. This is the reason and purpose that sizeof exists. In this case the best practice will be to use:

    char * charStringB = malloc(sizeof(*charStringB)*100);
    

    Note that *charStringB is same as char but this gives you the flexibility that if you want to change the type in future then there is fewer number of places where you need to remember to make modifications.

提交回复
热议问题