C pointers and bit setting issue

As a background for this question, it was a test program that I wrote to investigate the strange behavior that we observe in the messaging program I'm working on. We have various structures that use bit flags to store message states, some of the flags use char, some use shorts. The utility that we should dump messages into flat files used char * for these flag values ​​to retrieve the settings, so I deliberately used a different pointer to flag2.

When this program runs on AIX UNIX 6.1, why is this output:

2 set
4 set
8 set
16 set
64 sets

What happened to values ​​1 and 32?

#include <stdio.h>

#define SET(x,y) y |= (x)
#define UNSET(x,y) y &= (~x)

int main ( int argc, char *argv[] )
{
    unsigned char *g;
    unsigned short *h;
    unsigned long *i;

    char flag1; 
    short flag2; 
    long flag3;

    g = (char*) &flag2;

    SET(1, flag2);
    if ( 1 & *g )
        printf("1 set\n");
    UNSET(1, flag2);

    SET(2, flag2);
    if ( 2 & *g )
        printf("2 set\n");
    UNSET(2, flag2);

    SET(4, flag2);
    if ( 4 & *g )
        printf("4 set\n");
    UNSET(4, flag2);

    SET(8, flag2);
    if ( 8 & *g )
        printf("8 set\n");
    UNSET(8, flag2);

    SET(16, flag2);
    if ( 16 & *g )
        printf("16 set\n");
    UNSET(16, flag2);

    SET(32, flag2);
    if ( 32 & *g )
        printf("32 set\n");
    UNSET(32, flag2);

    SET(64, flag2);
    if ( 64 & *g )
        printf("64 set\n");
    UNSET(64, flag2);

    return 0;
}
+3
3

AIX - endian, , g flag. , g.

flag2 , arbirary. , , , arbirary, .

, x86, , .

+4

, .

  • flag2

  • , g= (short * ) &flag2, char 8 .

0

wikipedia :

C 2005 , (6.3.2.3 , . 7): [3]

char *external_buffer = "abcdef";
int *internal_data;

internal_data = (int *)external_buffer;  // UNDEFINED BEHAVIOUR if "the resulting pointer
                                         // is not correctly aligned"

:

, , .

++ 03 $5.3.3/1 ,

sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the

sizeof, (3.9.1) . [: , sizeof (bool) sizeof (wchar_t) -defined.69)

: ++

0

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


All Articles