pointers-memory · advanced · ~15 min
Understand pointer aliasing rules, optimize memory loops, and use the restrict keyword.
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.
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);
dest == NULL, a == NULL, b == NULL, total_sum == NULL, or count == 0, return -1.dest == a or dest == b, return -1.total_sum == dest, return -1.*total_sum = 0.i from 0 to count - 1:prod = a[i] * b[i].dest[i] = prod.prod to *total_sum.0 on success.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
dest, a, b, total_sum: pointers qualified with restrict; count: element count.
Returns 0 on success, or -1 on invalid inputs / aliasing violation.
Must use C99 restrict qualifiers on all pointer arguments.
#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;
}
Neglecting aliasing check between dest and total_sum; uninitialized sum.
Aliased pointers return -1; negative products accumulate correctly; count == 0 returns -1.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.