malloc 的最佳实践是什么? [英] What is the Best Practice for malloc?

查看:36
本文介绍了malloc 的最佳实践是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果以下任何一项是正确的并且被认为是创建能够容纳 100 个字符的 char 字符串的最佳做法,那么哪一项是正确的?

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);

推荐答案

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. char 的大小由 C 标准保证为一个字节.
  2. void 指针可以分配给任何指针,而无需在 C 中进行显式强制转换,并且强制转换是不必要的.强制转换 malloc 的返回值被认为是一种不好的做法,原因如下:
  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:

强制转换 malloc 的返回值有什么问题?

上述答案适用于 OP 中提到的选项.更好的做法是使用 sizeof 而不对任何 type 的大小做任何假设.这就是 sizeof 存在的原因和目的.在这种情况下,最佳做法是使用:

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);

请注意,*charStringBchar 相同,但这为您提供了灵活性,如果您想在将来更改 type需要记住进行修改的地方更少.

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.

这篇关于malloc 的最佳实践是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆