铸造空指针 [英] Casting void pointers

查看:140
本文介绍了铸造空指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了很多中老年C code中的以下内容:

  type_t * X =(type_t *)malloc的(...);

什么是铸造从返回的指针的malloc点(),因为它是无效* ?难道是因为旧的C编译器不支持空指针和用于返回的malloc() 的char * 而不是<? / p>

解决方案

您自己的解释是正确的。 pre-ANSI C(K&安培; R'C)没有一个无效* 键入与隐式转换。 的char * 加倍作为一个伪无效* 类型,但你需要一个类型转换的显式转换。

在现代的C铸造是建立在,因为它可以燮preSS编译器警告的malloc 的失踪原型皱起了眉头。在C ++中,铸件需要(但你应该使用而不是中的malloc 的大部分时间)。

更新

我的低于注释试图解释为什么需要投得有点不清楚,我会试着更好地在这里解释。你可能会认为,即使的malloc 收益的char * ,不需要投,因为它是类似于:

 为int *一个;
字符* B = A;

但是,在这个例子中,还需要一个铸造。第二行是一个的约束违反的很简单赋值运算符(C99 6.5.1.6.1)。这两个指针操作数必须是兼容的类型。当您更改为:

 为int *一个;
字符* B =(字符*)一个;

约束违反消失(两个操作数现在有键入的char * ),并将结果明确定义(用于转换为字符指针)。在相反的情况':

 的char * C;
为int * D =(INT *)C;

同样的论点搁置投,但是当为int * 的char *严格对齐要求中,结果的实现定义

结论:在pre-ANSI天类型转换是必要的,因为的malloc 返回的char * 而不是铸造的结果是违反约束的'='运算符。

I've seen a lot of the following in older C code:

type_t *x = (type_t *) malloc(...);

What's the point of casting the pointer returned from malloc() since it's void *? Is it because older C compilers didn't support void pointers and malloc() used to return char * instead?

解决方案

Your own explanation is the right one. Pre-ANSI C ('K&R' C) did not have a void * type with implicit conversion. char * doubled as a pseudo void * type, but you needed the explicit conversion of a type cast.

In modern C the casting is frowned upon because it can suppress compiler warnings for a missing prototype of malloc. In C++, the casting is needed (but there you should be using new instead of malloc most of the time).

Update

My comments below that try to explain why the cast is required were a bit unclear, I'll try to explain it better here. You might think that even when malloc returns char *, the cast is not needed because it is similar to:

int  *a;
char *b = a;

But in this example a cast is also needed. The second line is a constraint violation for the simple assignment operator (C99 6.5.1.6.1). Both pointer operands need to be of compatible type. When you change this to:

int  *a;
char *b = (char *) a;

the constraint violation disappears (both operands now have type char *) and the result is well-defined (for converting to a char pointer). In the 'reverse situation':

char *c;
int  *d = (int *) c;

the same argument hold for the cast, but when int * has stricter alignment requirements than char *, the result is implementation defined.

Conclusion: In the pre-ANSI days the type cast was necessary because malloc returned char * and not casting results is a constraint violation for the '=' operator.

这篇关于铸造空指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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