Edwin Skeevers
Edwin Skeevers

Reputation: 319

Does dereferencing pointer cast violate strict aliasing?

Does this violate strict aliasing (or any other spec rules)?

void *get_int_ptr(void)
{
    static int ival = 0;
    return (void*)&ival;
}

#define GET_INT() *((int*)get_int_ptr())

void main()
{
    GET_INT() = 123;
    printf("%i", GET_INT());
}

This is a simplification, the actual code works with members of a discriminated union.

Upvotes: 0

Views: 82

Answers (1)

Ted Lyngmo
Ted Lyngmo

Reputation: 117298

Does this violate strict aliasing (or any other spec rules)?

No it does not. From the C23 draft:

[6.3.2.3 Pointers]

  1. A pointer to void may be converted to or from a pointer to any object type. A pointer to any object type may be converted to a pointer to void and back again; the result shall compare equal to the original pointer.

Upvotes: 3

Related Questions