Answer to Question 22A-2

When p is created, a new int is allocated and p is made to point to that integer. Then p is immediately changed to point to the same address as A. The memory that was allocated leaks away.

A little thought reveals that the sum function should not allocate any memory. Here is a version that works, without a memory leak.

  // sum(A,n) returns A[0] + A[1] + ... + A[n-1].

  int sum(const int* A, int n)
  {
    int  s = 0;
    int* p;
    for(p = A; p < A + n; p++)
    {
      s = s + *p;
    }
    return s;
  }