Allocating memory for a part of structure

后端 未结 2 362
轮回少年
轮回少年 2021-01-12 01:16

I have the following example

#include 
#include 
#include 

typedef struct test{
    int a;
    long b;
    in         


        
2条回答
  •  逝去的感伤
    2021-01-12 02:02

    From C2011, paragraph 6.2.6.1/4:

    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.

    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.

    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 [...].

    (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.

提交回复
热议问题