It it UB to read some contiguous array cells as a larger type?

Viewed 59
char foo[n] = /*init here*/;  // n = 4*k + 4.
int i = 0;
while (i < n) {                            
   int four_bytes = *reinterpret_cast<const int*>(foo + i); // is this UB?
   bar(four_bytes);
   i += 4; 
}

In this snippet of code (assuming all data is initted properly, and that the array's length is a multiple of 4), is this reinterpret_cast UB?

C++14 and someetimes C++11

1 Answers

Alignment

It is UB when the char foo[n] is not sufficiently aligned as an int array.

Size1

When 0 < n < sizeof(int), *reinterpret_cast<const int*>(foo + i); attempts to refence outside foo[].


1 Did not see "array's length is a multiple of 4" until later. Yet this still applies on unusual platforms where the sizeof int is larger, say 8. (eg. some graphics process of old). IOWs "array's length is a multiple of 4" is not specified the same as "array's length is a multiple of sizeof(int)"

Related