Is this code well-defined behavior, in terms of strict aliasing?
_Bool* array = malloc(n);
memset(array, 0xFF, n);
_Bool x = array[0];
The rule of effective type has special cases for memcpy
and memmove
(C17 6.5 §6) but not for memset
.
My take is that the effective type becomes unsigned char
. Because the second parameter of memset
is required to be converted to unsigned char
(C17 7.24.6.1) and because of the rule of effective type, (C17 6.5 §6):
...or is copied as an array of character type, then the effective type of the modified object for that access and for subsequent accesses that do not modify the value is the effective type of the object from which the value is copied, if it has one.
- Question 1: What is the effective type of the data stored in
array
after thememset
call? - Question 2: Does the
array[0]
access therefore violate strict aliasing? Since_Bool
is not a type excluded from the strict aliasing rule (unlike character types).
array[0] == true
is not often used and considered to verbose, I think it should still be valid. And with yourmemset
call that comparison will actually be false. – Dropsondex
any value, or crash and burn for that matter. – Bacteriophage_Bool
, however, the representation in the memory may not be valid. Possiblymemset(array,(unsigned char)false, n);
would make it valid. – Lumbye_Bool *
so the memory will be interpreted as_Bool
. – Lumbye0
and readingint
s out of it would also be UB. IMO that would not have been anyone's intent, and this is yet another case of the strict aliasing rule being woefully underspecified. – Nonparticipating(unsigned char)false
has value0
and not1
. And effectively the cast serves nothing since when passing the argument, it is converted toint
, anyhow. – Phellem(unsigned char)true
.errno == ENOCOFEE
– Bamberg