Home > Blockchain >  Does passing to a function two pointers pointed to members of the same union violate the strict alia
Does passing to a function two pointers pointed to members of the same union violate the strict alia

Time:09-17

Note: learning the strict aliasing rule. Please be patient.

Code sample (t935.c):

#include <stdio.h>

int f(int* pi, double* pd)
{
    *pi = 13;
    *pd = 7E-323;
    return *pi;
}

int main(void)
{
    union { int i; double d; } u;
    printf("%d\n", f(&u.i, &u.d));
    return 0;
}

Invocations:

$ gcc t935.c -Wall -Wextra -std=c11 -pedantic  && ./a.exe
14

$ gcc t935.c -Wall -Wextra -std=c11 -pedantic -O2 && ./a.exe
13

$ gcc t935.c -Wall -Wextra -std=c11 -pedantic -O2 -fno-strict-aliasing && ./a.exe
14

Question: does passing to a function two pointers pointed to members of the same union violate the strict aliasing rule?

The question is originated from Unions and type-punning.

UPD20210901

what would happen if the union type was defined at global scope?

For "union u is defined at global scope" (actually file scope) case both gcc and clang show the same results as reported above for gcc.

CodePudding user response:

This is a defect in the C standard. See Defect Report 236.

The aliasing rule in 6.5 7 is intended to allow a compiler to assume pointers to two types that do not satisfy the rule refer to “different” objects, but the rule fails to adequately provide for union members (and also, per the defect report, objects in dynamically allocated memory). Taking the addresses of two union members may yield pointers to two types that may not alias according to the aliasing rule but that refer to the same memory. Thus, the C standard is broken in this regard, and the C committee has not corrected the problem.

  • Related