简体   繁体   English

检查两个指针​​是否在同一块内存中

[英]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. 给定一个方法,它接受两个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. 如果是情况一,则如果它们在同一个块中,我将返回1,否则返回0。 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: 这是我对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. 假设您知道内存的块有多大(我假设为1k(2 ^ 10)),则可以从较大的块中减去较小的地址,然后查看差值是否小于块大小-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;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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