简体   繁体   中英

Checking whether two pointers are in the same block of memory

This is a homework question that I am confused on how to approach. There are restrictions as well were I cannot use /, %, or any loops. Given a method, it accepts two pointers of type int. Taking these two pointer I need to find whether they are in the same block of memory or in different block of memory. If case one I return 1 for them being in the same block if and 0 otherwise. So my thinking is that if two pointers are in the same block of memory that must mean they point to the same integer? Im not sure if this is correct any hint in the right direction would be greatly appreciated.

Thank you

Floris basically gave you the idea; here's my actual implementation for POSIX:

uintptr_t pagesz = getpagesize();
uintptr_t addr_one = (uintptr_t)ptr1;
uintptr_t addr_two = (uintptr_t)ptr2;

bool in_same_page = (addr_one & ~(pagesz - 1)) == (addr_two & ~(pagesz - 1));

Assuming that you know how large the blocks of memory are (I assume 1k (2^10)) you can subtract the smaller address from the larger and see if the difference is less than the block size -1.

int same_block(int x, int y){

   int difference;

   if(x > y){
      difference = x - y;
   } else {
      difference = y - x;
   }

   if(difference < 1024){
      return 1;
   }

   return 0;

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM