Consider the following matrix addition code: MatrixAdd(int **a, int **b, int…

Consider the following matrix addition code:

MatrixAdd(int **a, int **b, int n) {
   for (i = 0; i < n; i++)
       for (j = 0; j < n; j++)
           a[j][i] += b[j][i];
}

The matrices a and b are dynamically allocated row by row as shown below:

MatrixAllocate(int n) {
   a = malloc(n * sizeof *a);
   for (i = 0; i < n; i++)
       a[i] = malloc(n * sizeof *a[i]);
   return a;
}

The system implements virtual memory with paging and a TLB to reduce memory access time. Which option is correct when the matrix addition code runs on this system?

Answer: D. The system performance may be degraded because the access pattern causes many TLB misses and reloads.The matrices are allocated row by row, but the code accesses them column by column using a[j][i] in the inner loop. Consecutive accesses therefore jump…

  1. A.

    The system performance will not be degraded because a TLB is implemented.

  2. B.

    The system performance will not be degraded because paging and the TLB are irrelevant when the code runs.

  3. C.

    The system performance may be degraded due to dynamic memory allocation using malloc().

  4. D.

    The system performance may be degraded because the access pattern causes many TLB misses and reloads.

Show answer & explanation

Correct answer: D

The matrices are allocated row by row, but the code accesses them column by column using a[j][i] in the inner loop. Consecutive accesses therefore jump between different rows instead of moving through contiguous elements. This poor locality can cause many TLB misses and reloads, degrading performance. Swapping the loop order so that the inner loop walks across columns within the same row would improve locality.

Explore the full course: Wipro Preparation

Loading lesson…