Base and limit check

The simplest memory protection gives each process two registers set by the OS: a base (where its memory starts) and a limit (how big it is). The MMU checks every address before it goes out.

What to build

Translate logical addresses with a base and a limit register, and trap the ones outside the process.

Requirements

  • A logical address a is valid when 0 ≤ a < limit. Its physical address is base + a.
  • For each address print the physical address, or trap when the address is not valid.

Input

The first line has base and limit (1 ≤ limit ≤ 100000, 0 ≤ base ≤ 1000000). The second line has q (1 ≤ q ≤ 30), and the third line has q logical addresses (−1000 to 200000).

Output

One line per address: the physical address, or trap.

Constraints

All numbers fit in an int.

Example

Input:

30000 12000
4
0 1024 11999 12000

Output:

30000
31024
41999
trap

Why it works

One comparison and one addition are all the MMU does. Because every access is checked, a process cannot touch memory outside base to base + limit − 1, even if it computes a wild address. The check also catches negative numbers.

Examples

Example 1 · Input
30000 12000
4
0 1024 11999 12000
Expected output
30000
31024
41999
trap
Example 2 · Input
500 10
3
-1 9 10
Expected output
trap
509
trap

Hints

Hint 1

A logical address is good when 0 <= address < limit. The physical address is base + address.

Hint 2

For a bad address print trap and do not compute anything.

Hint 3

Read all addresses with a loop and scanf("%d", &address).

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>

int main(void) {
    int base, limit, q, a;
    scanf("%d %d", &base, &limit);
    scanf("%d", &q);
    for (int i = 0; i < q; i++) {
        scanf("%d", &a);
        if (a < 0 || a >= limit) printf("trap\n");
        else printf("%d\n", base + a);
    }
    return 0;
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: Memory: addresses and allocation →