I am trying to study for an exam..and I found this example but can\'t understand how they got the answer. Can anyone explain it please?
Question:
The key here is to see how all the array accesses look when reading from linear memory addresses. Row-major (C) order also has to be assumed for the answer to make sense. The problem also left out units, which we'll assume are bytes (so A has to be held in 1-byte types).
char *B = &(A[0][0]); (memory address 200)
Accessing A[i][j]
is now equivalent to B[i*100 + j]
or *(200 + i*100+j)
(row-major order).
Two pages can fit in memory. One is taken by the program (bytes 0-199 - also the C convention). The other is for accessing A, which spans 100*100 bytes / (200 bytes / page) = 50 pages.
Since 0-199 is always in memory, the other page will address n*200 to (n+1)*200-1, where n is some integer -- corresponding to 2 rows of A at a time.
Finally, at a page fault, the least recently used (LRU) algorithm would have just read an instruction from page 0-199, so would always discard the page holding the old part of A to read the new part of A (when n changes, every 2 rows).
So you can easily see what's happening by reading down rows of a 100x100 matrix -- every 2 rows swaps a page, and this is repeated 100x in the outer loop (left-to-right across a row). This leads to 100x50 page-faults.
In the real world, you can track page faults with linux commands or getrusage.