Lecture 004

-1 only when dividing int_min()/-1 Other division by -1 is fine

[any_number]/0 [any_number]%0

Memory

frame: Local Memory. (stack)

active frame: the local memory in a function that is currently running.

Local Memory:

Allocated Memory

Creating Array

int[] A = alloc_array(int, 5);

Modifying Array

re-assign variable

Comparing Array

Comparing array only compares its address, never compare

Garbage Collecting

When no address point to array, array gets garbage collected. (we don't de-allocate array)

Copying Array

Wrong ways of copying array

Wrong ways of copying array

Bad code for passing requires

int[] array_copy(int[] A, int n)
@//requires n>=0
{
  int[] B = alloc_array(int, n);
  return B;
}

int[] array_copy(int[] A, int n)
//@requries n == \length(A);
{
  int[] B = alloc_array(int, n);
  B = A;
  return B;
}

A Working Solution TODO

int[] array_copy(int[] A, int n)
//@requires n == \length(A)
{
  int[] B = alloc_array(int, n);
  for (int i=0; i<n; i++) {
    B[i] = A[i];
  }
  return B;
}

int main() {
  int[] I = ...[5, 6, 7]...;
  int[] J = array_copy(I, 3);
  return 0;
}

Proving Safety

Contracts of Array Operations

alloc_array(type, n)
//@requires n >= 0;
//@ensures \length(\result) == n;

A[i]
//@requires 0 <= i
//@requires i < \length(A);

\length(A)
//@ensures \result >=0;

Safety

Precondition

Good Code

int[] array_copy(int[] A, int n)
//@requires n == \length(A);
//@ensures \length(\result)==n;
{
  int[] B = alloc_array(int, n);
  for (int i=0; i<0; i++) {
    //@loop_invariant 0<=i;
    B[i]=A[i];
  }
  return B;
}

Proving Correctness

  1. length correct

    length correct
  2. write testing code
  3. ensure you don't modify given array
  4. making ensure as complicated as the function itself (not suggested)

(x/y)*y + (x%y) = y 0 <= |x%y| < |y| x/y rounds towards 0.


writing 2 due Monday programming 2 due Thursday bit patterns interfaces

TODO re-watch Q&A section

Table of Content