为联合分配内存以及联合指针和指针联合之间的区别 [英] Allocating memory for unions and difference between union pointer and union of pointers

查看:70
本文介绍了为联合分配内存以及联合指针和指针联合之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我的问题此处无法自信地回答,我希望在这里再次提问某人肯定知道:

Since my question here couldn't be confidently answered, I ask here again in hope that someone knows for sure:

  1. 指向联合的指针与包含指向其元素的指针的联合之间是否存在任何区别(在语法上)?示例中生成的程序集是相同的.
  2. 只要我从不访问其他成员,是否可以只为其中一个成员(不是最大的)分配内存?
  1. Is there any difference (besides syntactical) between a pointer to a union and a union that contains pointers to its elements? The generated assembly in this example is identical.
  2. As long as I'm never accessing the other members, is it allowed to allocate memory for only one of the members (which isn't the largest)?

关于第二个问题,C89草案的6.5.2.1说:

Regarding the 2nd question, 6.5.2.1 of the C89 draft says:

联合的大小足以容纳其最大的成员-最多可以随时将一个成员的值存储在联合对象中.适当地转换后的联合对象的指针指向其每个成员(或者,如果一个成员是位字段,则指向它所在的单元),反之亦然.

The size of a union is sufficient to contain the largest of its members - The value of-at most one of the members can be stored in a union object at any time. A pointer to a union object suitably converted points to each of its members (or if a member is a bit-field. then to the unit in which it resides) and vice versa.

因此,至少在正确地进行转换时,只为其中一个成员分配空间应该没问题,但是我找不到任何能够保证在使用联合时仅使用被访问成员的相应位的任何东西.

So, at least when properly cast, it should be fine to only allocate space for one of the members, but I couldn't find anything that guarantees that only the corresponding bits of the accessed member are used when using a union.

给出以下定义:

typedef struct s1
{
    int a;
} s1;

typedef struct s2
{
    int a;
    int b;
} s2;

union u1
{
    s1 a;
    s2 b;
};

这合法吗?

union u1 *u = malloc(sizeof(s1));
u->a.a = 3;
printf("s1.a=%d\n", u->a.a);
printf("s2.a=%d\n", u->b.a);

推荐答案

我认为您误解了指向工会的指针.

I think you are misunderstanding the pointer-to-union thing.

使用示例代码的一部分(您应该在问题正文中确实包含该代码)

Using a part of your example code (which you should really have in the question body)

union u1
{
    s1 a;
    s2 b;
};

那么就拥有

union u1 my_union;

您可以保证& my_union 等于& my_union.a & my_union.b .

关于

union u1 *u = malloc(sizeof(s1));
u->a.a = 3;
printf("s1.a=%d\n", u->a.a);
printf("s2.a=%d\n", u->b.a);

这仅能工作是因为两个原因:允许使用联合进行类型处理,并且 u-> aa u-> ba 完全相同大小和完全相同的位置.我的看法是,从技术上讲,它是UB,但由于其他要求而起作用.

This only works because of two reasons: Type-punning is allowed using unions, and both u->a.a and u->b.a are the exact same size and at the exact same position. The way I see it is that technically it's UB but works because of other requirements.

如果您尝试访问 u-&b; b.b ,则UB将得到保证.

If you attempted to access u->b.b the UB would be guaranteed.

这篇关于为联合分配内存以及联合指针和指针联合之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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