pointers-memory · advanced · ~15 min

Restrict Pointer Aliasing Optimization

Understand pointer aliasing rules, optimize memory loops, and use the restrict keyword.

Challenge

In C99, the restrict type qualifier promises the compiler that the pointer is the sole reference to the memory block within its scope. Without restrict, pointer aliasing forces the compiler to reload memory on every loop iteration, preventing vectorization.

Your Task

Implement an optimized element-wise vector multiply and accumulate:

int vector_multiply_accumulate(int * restrict dest,
                               const int * restrict a,
                               const int * restrict b,
                               size_t count,
                               int * restrict total_sum);

Rules

  1. If dest == NULL, a == NULL, b == NULL, total_sum == NULL, or count == 0, return -1.
  2. Detect potential pointer overlap (aliasing violation):
    • If dest == a or dest == b, return -1.
    • If total_sum == dest, return -1.
  3. Initialize *total_sum = 0.
  4. For each element i from 0 to count - 1:
    • Compute product: prod = a[i] * b[i].
    • Store dest[i] = prod.
    • Add prod to *total_sum.
  5. Return 0 on success.

Example

int a[] = {2, 3, 4};
int b[] = {5, 6, 7};
int dest[3];
int sum = 0;
vector_multiply_accumulate(dest, a, b, 3, &sum); // returns 0, dest={10, 18, 28}, sum=56

Input format

dest, a, b, total_sum: pointers qualified with restrict; count: element count.

Output format

Returns 0 on success, or -1 on invalid inputs / aliasing violation.

Constraints

Must use C99 restrict qualifiers on all pointer arguments.

Starter code

#include <stddef.h>

int vector_multiply_accumulate(int * restrict dest,
                               const int * restrict a,
                               const int * restrict b,
                               size_t count,
                               int * restrict total_sum) {
    (void)dest; (void)a; (void)b; (void)count; (void)total_sum;
    return -1;
}

Common mistakes

Neglecting aliasing check between dest and total_sum; uninitialized sum.

Edge cases to handle

Aliased pointers return -1; negative products accumulate correctly; count == 0 returns -1.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.