Today, I encountered a piece of C code that looked pretty much like this:
void my_func(unsigned int *);
int main() {
unsigned int a[8];
// init_a(a); => a is properly initialized
my_func(a);
}
void my_func(unsigned int * a) {
unsigned int * array_begin = a;
a += 8; // HERE
while (a-- > array_begin) {
unsigned int tmp = *a;
*a = (tmp >> 1);
// other stuff
}
}
From my understanding, the line a += 8
brings the pointer right after the end of the array. Then, in the loop condition, the pointer is decremented from this "past array address", dereferenced in the loop body. No problem, because at this point the pointer is back inside the array.
The code compiled and ran without any problems, unit tests were successful.
Still, my question is : is it legal C to move the pointer after the array, and then decrement it to be back inside the allocated object, or is this an undefined behavior ?