What type of shooting / pointer magic is defined by the standard?

I don't seem to be able to wrap my head around some parts of the C standard, so I come here to clarify the vague, disturbing uncertainty that arises when I have to think about which such tricks are determined by behavior and that are undefined or violate the standard. I do not care if this will work, I do not care if the standard C considers this legal, specific behavior.

One that I'm pretty sure is UB:

struct One
{
        int Hurr;
        char Durr[2];
        float Nrrr;
} One;

struct Two
{
        int Hurr;
        char Durr[2];
        float Nrrr;
        double Wibble;
} Two;

One = *(struct One*)&Two;

, . , int * .. , , . , , , , C89 C99. C11 , IMHO.

+4
3

C99 6.7.2.1 :

5

6.2.5, , ,

12

, , , .

13

, , . , , ( -, , ) . ,

( int * ).

- "Downcast" a Two* One* - . , , One Two .

, , , , ( , ).

, , , :

struct One
{
        int Hurr;
        char Durr[2];
        float Nrrr;
} One;

struct Two
{
        struct One one;
        double Wibble;
} Two;

, Two* One* - 13. - . :

One = Two.one;
0

, UB. , gcc, clang -pedantic.

C99 ( 6.5.2.3/6) : [1]

union OneTwo {
  struct One one;
  struct Two two;
};

OneTwo tmp = {.two = {3, {'a', 'b'}, 3.14f, 3.14159} };
One one = tmp.one;

, "" struct One union , , struct Two struct One. union, , union, union , struct.

, C ( , , C++) (& sect; 6.2.6.1/4) [2]. , :

struct One one;
struct Two two = ...;
unsigned char tmp[sizeof one];
memcpy(tmp, two, sizeof one);
memcpy(one, tmp, sizeof one);

void*, , , , :

struct One one;
struct Two two = ...;
unsigned char tmp[sizeof one];
memcpy(one, two, sizeof one);

, OP, , : , , a struct Two* a struct One*. (& sect; 6.3.2.3/7) [3], , , , . , , struct Two ( ) struct One - . :

one = *(struct One*)(void*)&two;

.

. , , . ; one two. , two , .

, , . , , , struct One*, struct Two , , , . , struct One, struct Two, - union.

--- :

[1] ", , (. ), , ."

[2] ", , n × CHAR_BIT , n - , . unsigned char [n] (, memcpy) & hellip; "

[3] " & hellip; , . , , ."

+1

A1. Undefined, - Wibble. A2. .

S9.2 N3337.

( 9) , ( )

, , , Wibble. : Wibble Two.

, reinterpret_cast, ( -, , ) .

, , int.

-1

Source: https://habr.com/ru/post/1526462/


All Articles