难道我投malloc的结果? [英] Do I cast the result of malloc?
问题描述
在<一个href=\"http://stackoverflow.com/questions/571945/getting-a-stack-overflow-exception-when-declaring-a-large-array\">this问题,有人在评论中建议我的的不的投的malloc
的结果,即的:
In this question, someone suggested in a comment that I should not cast the results of malloc
, i.e:
int *sieve = malloc(sizeof(int)*length);
而不是:
int *sieve = (int *)malloc(sizeof(int)*length);
为什么会是这种情况?
Why would this be the case?
推荐答案
否;您的不的投出结果,因为:
No; you don't cast the result, since:
- 这是不必要的,因为
无效*
自动,安全地提升到在这种情况下任何其他指针类型。 - 它可以隐藏一个错误,如果你忘了,包括
&LT;&stdlib.h中GT;
。这可能会导致崩溃(或者更糟,的不的导致崩溃,直到后来的方式在code的一些完全不同的一部分)。试想,如果指针和整数为不同大小会发生什么;那么你通过铸造隐藏警告,可能会失去你的返回地址位。 - 它增加混乱到code,强制转换不是很容易阅读(特别是如果该指针类型是长)。
- 这让你重复自己,这是普遍不好。
- It is unnecessary, as
void *
is automatically and safely promoted to any other pointer type in this case. - It can hide an error, if you forgot to include
<stdlib.h>
. This can cause crashes (or, worse, not cause a crash until way later in some totally different part of the code). Consider what happens if pointers and integers are differently sized; then you're hiding a warning by casting and might lose bits of your returned address. - It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
- It makes you repeat yourself, which is generally bad.
作为一个澄清,请注意,我说:你不要投,而不是你不要的需求的投。在我看来,这是一个失败,包括中投,即使你是正确的。有简单地做没有任何好处,但一帮潜在的风险,以及包括中投表示您不知道的风险。
As a clarification, note that I said "you don't cast", not "you don't need to cast". In my opinion, it's a failure to include the cast, even if you got it right. There are simply no benefits to doing it, but a bunch of potential risks, and including the cast indicates that you don't know about the risks.
另外请注意,评论家指出,约有直C,不是C以上的会谈++。我非常坚信C和C ++作为单独的语言。
Also note, as commentators point out, that the above talks about straight C, not C++. I very firmly believe in C and C++ as separate languages.
要进一步增加,你的code不必要的重复类型信息( INT
),这可能会导致错误。这是更好地取消引用所使用的指针来保存返回值,锁定两个一起:
To add further, your code needlessly repeats the type information (int
) which can cause errors. It's better to dereference the pointer being used to store the return value, to "lock" the two together:
int *sieve = malloc(length * sizeof *sieve);
这也是移动长度
来前增加知名度,并且丢弃原来的冗余括号的sizeof
;他们的只需要的当参数是一个类型的名字。许多人似乎并不知道(或忽略)这一点,这使得他们的code更详细。请记住:的sizeof
不是一个函数! :)
This also moves the length
to the front for increased visibility, and drops the redundant parentheses with sizeof
; they are only needed when the argument is a type name. Many people seem to not know (or ignore) this, which makes their code more verbose. Remember: sizeof
is not a function! :)
这篇关于难道我投malloc的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!