Suppose I need a function that checks whether two arbitrary buffers are interleaved*. One straightforward idea that comes to mind would be this:
bool isInterleaved(uint* buf1, // pointer to first buffer
uint* buf2, // pointer to second buffer
uint len1, // length of first buffer
uint len2, // length of second buffer
uint stride1, // stride length of first buffer
uint stride2) // stride length of second buffer
{
... // first some sanity checks like (NULL != buf), (0U < len),...
bool retval = false;
if ((len1 == len2) && (2U == stride1) && (2U == stride2))
{
if ((&buf1[1] == &buf2[0]) ||
(&buf2[1] == &buf1[0]))
{
retval = true;
}
}
return retval;
}
On paper, it looks good enough, quick tests were positive. However, In C and C++, the comparison of pointers to objects is only strictly defined if the pointers point to members of the same object, or elements of the same array.
Does my example - specifically the line with (&buf1[1] == &buf2[0])
and the one after - constitute undefined behavior? If yes, how could I implement a check like this without relying on undefined behavior?
*see edit history for an example of interleaved data or check the wikipedia article on interleaving. It is not 'a wrong word', as a comment suggests.