In C and C ++, it is often useful to use a pointer to the past to write functions that can work on arbitrarily large arrays. C ++ gives an overload of std::end to make this easier. In C, on the other hand, I often found to see a macro defined and used as follows:
#define ARRAYLEN(array) (sizeof(array)/sizeof(array[0]))
I also saw the arithmetic pointer trick used to make such functions work on individual objects:
int b; do_something (&b, &b + 1);
It seemed to me that something similar could be done with arrays, since they are considered by C (and, in my opinion, C ++) to be "full objects". Given the array, we can get a pointer to the array immediately after it, dereference this pointer and use the conversion of the array to a pointer in the resulting array reference to get a pointer to the end of the original array:
#define END(array) (*(&array + 1))
My question is this: When dereferencing a pointer to a nonexistent array object, does this code exhibit undefined behavior? . I am wondering what recent changes both C and C ++ have to say about this code (not because I intend to use it, because there are better ways to achieve the same result, but because it is an interesting question).
c ++ c undefined-behavior c11 c ++ 11
Stuart Olsen
source share