为什么使用更安全的sizeof(*指针)中的malloc [英] Why is it safer to use sizeof(*pointer) in malloc

查看:125
本文介绍了为什么使用更安全的sizeof(*指针)中的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.

推荐答案

它是安全becuse你没有提到的类型名称两次,并没有搭建类型的引用的版本拼写正确。例如,你不必为数星星,在

It is safer becuse you don't have to mention the type name twice and don't have to build the proper spelling for "dereferenced" version of the type. For example, you don't have to "count the stars" in

int *****p = malloc(100 * sizeof *p);

与此相比,该型为主的sizeof

int *****p = malloc(100 * sizeof(int ****));

在这里你有太多确保使用正确数量的 * 的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.

这篇关于为什么使用更安全的sizeof(*指针)中的malloc的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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