Search code examples
clanguage-lawyerundefined-behaviorstrict-aliasing

Is it undefined behavior to access the object representation of a pointer through a char*?


I know this is weird question, but just bad curious.

char* ptr = 0;
strcpy( (char*) &ptr, "UB?");

This code means 'I will use the memory of ptr as a char array.' I think 'it's absolutely UB', but someone says 'it's not UB until you dereference'. It is not UB? How can this awful code not be UB?


Solution

  • C17 §6.5 paragraph 6 includes:

    The effective type of an object for an access to its stored value is the declared type of the object, if any. [...]

    The effective type of the object denoted by ptr is char *.

    Paragraph 7 includes:

    An object shall have its stored value accessed only by an lvalue expression that has one of the following types:

    • a type compatible with the effective type of the object,
    • a qualified version of a type compatible with the effective type of the object,
    • a type that is the signed or unsigned type corresponding to the effective type of the object,
    • a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,
    • an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or
    • a character type.

    The object denoted by ptr is having its stored value accessed by an lvalue expression of character type (via the strcpy function which interprets characters as if they had type unsigned char). This is not UB.