Expedia Interview Question
Software Engineer / DevelopersSimilar Question was asked to me while I was interviewing with Intel. Here is the Question and my answer to it:
Q: The operating system typically allocates memory in pages such that the base address of the pages is 0, 4K, 8K, .... Given two (virtual) addresses, write a program to find if they refer to locations on the same page.
Ans
Since the page boundaries are at 0, 4, 8k …we can see that the page size is equal to 4K. Now assuming we have a 32 bit address space, bits 31-20 will always be the same for one block of 4k bytes of memory since 4k is equal to 4*1024 which is equal to 12 lower order bits of the address. Given two addresses the only thing to be checked is their bits from 31-20. If they are same that means both the addresses lie in the same page. (Assuming int size is 4 bytes else we will use long to store the address)
bool AreOnSamePage (int *a, int *b)
{
Unsigned int c = (unsigned int) a;
Unsigned int d = (unsigned int) b;
c = c & 0xFFFFF000; //masking the lower order 12 bits
d = d & 0xFFFFF000;
if(c==d)
return true;
else
false;
}
i agree with gaurav's soln above. expect that u need to make this one change to the explanation - the mask is on the 12 lower order bits, so you are checking if the bits 31-13 are the same and not 31-20 like he says. (assuming 31 is the MSB)
corrected solution:
bool AreOnSamePage (int *a, int *b)
{
unsigned int c = (unsigned int) a;
unsigned int d = (unsigned int) b;
c = c & 0x00000FFF; //Masking the LSB 12 bits
d = d & 0x00000FFF;
if(c==d)
return true;
else
false;
}
If you the Page size. then just see that the two addresses are within the Page size boundary or not.
- Jo May 04, 2007