为什么在 malloc 中使用 sizeof(*pointer) 更安全 [英] Why is it safer to use sizeof(*pointer) in malloc
问题描述
给定
struct node
{
int a;
struct node * next;
};
要 malloc 一个新的结构,
To malloc a new structure,
struct node *p = malloc(sizeof(*p));
比
struct node *p = malloc(sizeof(struct node));
为什么?我以为他们是一样的.
Why? I thought they are the same.
推荐答案
它更安全,因为您不必两次提及类型名称,也不必为取消引用"构建正确的拼写.类型的版本.例如,您不必数星星";在
It is safer because you don't have to mention the type name twice and don't have to build the proper spelling for the "dereferenced" version of the type. For example, you don't have to "count the stars" in
int *****p = malloc(100 * sizeof *p);
对比
int *****p = malloc(100 * sizeof(int ****));
你必须确保在sizeof
下使用了正确数量的*
.
where you have to make sure you used the right number of *
under sizeof
.
为了切换到另一种类型,您只需更改一个地方(p
的声明)而不是两个.而有将malloc
结果强制转换的习惯的人,要改三处.
In order to switch to another type you only have to change one place (the declaration of p
) instead of two. And people who have the habit of casting the result of malloc
have to change three places.
更一般地说,坚持以下准则是很有意义的:类型名称属于声明而不属于其他地方.实际的语句应该是类型无关的.他们应该尽可能避免提及任何类型名称或使用任何其他类型特定的功能.
More generally, it makes a lot of sense to stick to the following guideline: type names belong in declarations and nowhere else. The actual statements should be type-independent. They should avoid mentioning any type names or using any other type-specific features as much as possible.
后者意味着:避免不必要的转换.避免不必要的特定于类型的常量语法(例如 0.0
或 0L
,其中普通的 0
就足够了).避免在 sizeof
下提及类型名称.等等.
The latter means: Avoid unnecessary casts. Avoid unnecessary type-specific constant syntax (like 0.0
or 0L
where a plain 0
would suffice). Avoid mentioning type names under sizeof
. And so on.
这篇关于为什么在 malloc 中使用 sizeof(*pointer) 更安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!