Search code examples
clanguage-lawyerstrict-aliasing

Default type for object pointed by an integer constant


Given a memory address of ADDR_X where I have dedicated hw registers with some values, does address type-casting it will violate strict aliasing?

//lets use some arbitrary address for the sake of this example
#define ADDR_X 0xE0F0

void function(void)
{
    some_structure_type *my_struct_ptr = (some_structure_type *)ADDR_X;

    my_struct_ptr->a_field = 1;

    ...
}

Is there a default type for object pointed by an integer constant in which the casting to pointer to some_structure_type violates? is this code well defined by the standard (given the fact that the address is aligned to the structure size and no padding within the structure)?


Solution

  • Is there a default type for object pointed by an integer constant

    No - partly because integer constants don't point to anything.

    Pointers point to things, and pointers have types, and aliasing applies when you have pointers of different types pointing at the same storage.

    You only show one pointer here, of type some_structure_type*, so that location has one name, one type, and no aliases. The fact that the address is also stored in an int (or intptr_t or whatever) doesn't associate another type with it.

    You can read a description of the strict aliasing requirements here, but loosely, the practical problem occurs when you're writing to and reading from the same address through pointers of incompatible types, because the optimizer is allowed to assume you didn't do this.

    That means that even if you did have another pointer of incompatible type to the same location, it wouldn't be a problem unless you're storing through one pointer and loading through the other. Neither an integer constant, nor a char* or void* count as a "pointer of incompatible type" anyway.