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

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

问题描述

这意味着,如果任一下列的是正确的,将被视为创造能够容纳100个字符一个字符的字符串的最佳做法?

 的char * charStringA =的malloc(100);
字符* charStringB =的malloc(sizeof的(字符)* 100);
字符* charStringC =(字符*)malloc的(100);
字符* charStringD =(字符*)malloc的(的sizeof(字符)* 100);


解决方案

 的char * charStringA =的malloc(100);
字符* charStringB =的malloc(sizeof的(字符)* 100);

两者都同样正确。结果
应该在此评估被认为是很重要的两点是:


  1. 字符的大小是保证C标准一个字节。

  2. A 无效指针可以分配给任何指针没有C的一个显式的转换和铸造是不必要的。铸造的malloc的返回值被认为是因为以下的坏习惯:

这有什么错铸造的malloc的返回值?


以上回答适用于OP提到的选项。一个更好的做法是使用的sizeof 未做任何假设任何的键入的大小。这是的sizeof 存在的原因和目的。在这种情况下,最好的做法将是使用

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

注意 * charStringB 是一样的字符但是这给你的灵活性,如果你想改变的键入的未来则有较少的,你需要记住进行修改名额。

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. 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.

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

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