为一部分结构分配内存 [英] Allocating memory for a part of structure

查看:70
本文介绍了为一部分结构分配内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下示例

#include <stdlib.h>
#include <stdio.h>
#include <stddef.h>

typedef struct test{
    int a;
    long b;
    int c;
} test;

int main()
{
    test *t = (test*) malloc(offsetof(test, c));
    t -> b = 100;
}

它工作正常,但是我不确定.我想我在这里有UB.我们有一个指向结构类型的对象的指针.但是结构类型的对象并不是真的有效.

It works fine, but Im not sure about it. I think I have UB here. We have a pointer to an object of a structure type. But the object of the structure type is not really valid.

我通过了标准,找不到此行为的任何定义.我可以找到的唯一接近此部分的部分是6.5.3.2:

I went through the standard and could not find any definition of this behavior. The only section I could find close to this one is 6.5.3.2:

如果已将无效值分配给指针,则行为 一元*运算符未定义

If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined

但这并不重要,因为malloc返回的指针是完全有效的.

But this is not really relevant since the pointer returned by malloc is completely valid.

标准中是否有解释这种行为的参考文献?我正在使用C11 N1570.

Is there a reference in the standard explaining such a behavior? I'm using C11 N1570.

推荐答案

来自

存储在任何其他对象类型的非位字段对象中的值由n x CHAR_BIT位组成,其中n是该类型对象的大小(以字节为单位).

Values stored in non-bit-field objects of any other object type consist of n x CHAR_BIT bits, where n is the size of an object of that type, in bytes.

因此,由于代码中分配的对象小于struct test的大小,因此它不能包含该类型的对象的值.

Therefore, since the allocated object in your code is smaller than the size of a struct test, it cannot contain a value of an object of that type.

现在考虑您的表达式t -> b = 100. C2011,第6.5.2.3/4段定义了行为->运算符:

Now consider your expression t -> b = 100. C2011, paragraph 6.5.2.3/4 defines the behavior of the -> operator:

后缀表达式,后跟->运算符和标识符,指定结构或联合对象的成员.该值是第一个表达式指向的对象的命名成员 [...]的值.

A postfix expression followed by the -> operator and an identifier designates a member of a structure or union object. The value is that of the named member of the object to which the first expression points [...].

(添加了强调.)我们已经确定,您的t不会(实际上,不能)指向struct test,因此,关于6.5.2.3的说法是最好的/4是它不适用于您的情况. ->运算符的行为没有其他定义,我们剩下的是第4/2段(强调):

(Emphasis added.) We've established that your t does not (indeed, cannot) point to a struct test, however, so the best we can say about 6.5.2.3/4 is that it does not apply to your case. There being no other definition of the behavior of the -> operator, we are left with paragraph 4/2 (emphasis added):

如果违反了在约束或运行时约束之外出现的应"或不应"要求,则该行为未定义.未定义的行为在本国际标准中用未定义的行为" 一词表示,或者省略了对行为的任何明确定义 .

If a ''shall'' or ''shall not'' requirement that appears outside of a constraint or runtime- constraint is violated, the behavior is undefined. Undefined behavior is otherwise indicated in this International Standard by the words ''undefined behavior'' or by the omission of any explicit definition of behavior.

就这样.您的代码的行为是不确定的.

So there you are. The behavior of your code is undefined.

这篇关于为一部分结构分配内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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