klutt
klutt

Reputation: 31409

Is it possible to check if two pointers points to the same object?

Let's consider this code:

char arr[10];
char *ptr1 = &arr[0];
char *ptr2 = &arr[5];

or

int i;
char *ptr1 = &i;
char *ptr2 = ptr1 + 1;

Clearly, these two pointers points to the same object. But is there any way to determine this afterwards in code? Is it possible to write a function like this?

// Returns true if p1 and p2 points to the same object and false otherwise
bool same_object(void *p1, void *p2) {
    if(<condition>) 
        return true;
    return false;
}

I suspect this is impossible since you cannot retrieve the size of an array just from a pointer, but I wanted to make sure if there's something I may have overlooked.

Upvotes: 2

Views: 286

Answers (1)

Lundin
Lundin

Reputation: 214310

If you don't pass along the object address and size, or store them in file scope variables, then it isn't possible.

If you pass along the object and its size to a function, then it will be perfectly possible. Something similar to this is well-defined for a generic object (no matter if scalar, aggregate, union):

bool same_object (size_t         objsize, 
                  const uint8_t  obj [objsize], // pass any object cast to const uint8_t* here
                  const void*    p1, 
                  const void*    p2)
{
  uintptr_t start = (uintptr_t)obj;
  uintptr_t end   = start + objsize;
  uintptr_t i1    = (uintptr_t)p1;
  uintptr_t i2    = (uintptr_t)p2;

  return i1 >= start && 
         i1 < end    && 
         i2 >= start && 
         i2 < end;
}

This is under the assumption that exotic systems will not implement uint8_t and normal systems will implement uint8_t as a character type.

Upvotes: 1

Related Questions