Possible Duplicate:
checking if pointer points within an array
If I have an array and a size, and I want to check if a given pointer points to an element inside an array, is there any way to do so in standard C or C++ without invoking UB?
Does this work?
bool is_inside(someType * array, int size, someType * other_pointer){
for (int i = 0; i < size; i++)
if (array + i == other_pointer)
return true;
return false;
}
edit: It is my understanding that you cannot use comparisons other than == and != for pointers not pointing to the same array without UB (although in practice it works as expected). Was I wrong in this?
It depends on what you mean by UB.
Specifically, for pointer comparisons, section 5.9 “Relational Operators” of the C++ standard says:
Note that the behaviour is unspecified (meaning that the result of the comparison could be
trueorfalse– in other words the result doesn’t tell you anything useful – but the implementation isn’t required to specify which) as opposed to undefined (meaning that the compiler or the resulting program could do anything at all).However, so far I have only seen one family of implementations that didn’t do the expected thing with code like Kirill’s:
Those implementations are compilers intended for building MS-DOS real-mode programs, in which addresses have a paragraph and offset part. The addresses FF00:0010 and FF01:0000 point to the same memory location but if I recall correctly the compilers weren’t guaranteed to behave in the expected way, except when compiling for some memory models (certainly the HUGE model but perhaps others).
However, if either
porqdoes not point to an existing object (because for example the pointer was freed) then the behaviour is going to be undefined no matter what you do. So you can’t use this kind of method to figure out if a pointer is still valid.