Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

c - What is the Best Practice for malloc?

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 = malloc(100);
char * charStringB = malloc(sizeof(char)*100);
char * charStringC = (char*)malloc(100);
char * charStringD = (char*)malloc(sizeof(char)*100);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...