#!../src/tops  -i -s ../sys  -u ../usr
/*
Program Tops - a stack-based computing environment
Copyright (C) 1999-2006  Dale R. Williamson

Author: Dale R. Williamson <dale.williamson@prodigy.net>

File test/purge_mem February 2006

   Testing memory leakage when allocating and freeing large arrays in
   the catalog.

   Under AIX, this memory test balances to zero every time.

   Under Linux, this memory test does not always balance to zero, but
   the imbalance is very small compared to bytes allocated.

   Shown below is running this test ten times in RH 7.3.  Zero balance
   of memory allocated and memory freed is seen in four of the ten. In
   the other six, very small nonzero imbalances occurred.

   A negative balance, like -40, means 40 bytes were actually gained.
   Such small plus-and-minus values are assumed to be ok.

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Notice: catalog memory imbalance: -8 bytes out of 973552 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Notice: catalog memory imbalance: 16 bytes out of 1025816 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Ok: no catalog memory leak in 807816 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Ok: no catalog memory leak in 831336 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Notice: catalog memory imbalance: -16 bytes out of 973760 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Notice: catalog memory imbalance: 8 bytes out of 713384 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Ok: no catalog memory leak in 882032 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Ok: no catalog memory leak in 721352 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Notice: catalog memory imbalance: -40 bytes out of 641544 bytes

      [dale@clacker] /opt/tops/tops/test > purge_mem
       Notice: catalog memory imbalance: -16 bytes out of 955600 bytes
*/
   catmsg(no);
   time seedset

   function catalog_mem(M) {
   /* Create M random-sized matrices and book them to the catalog,
      then purge them and note the total memory change. */

      { m1 = 0; m2 = 0; }

      DO(M, 1) book(purged, suffix("A", I)); LOOP;
      memprobe1; // create the reference mem

      DO (M, 1) // book M matrices
         book(random(100*rand, 100*rand), suffix("A", I));
      LOOP;
      m1 = memprobe1; // plus mem 

      DO(M, 1) book(purged, suffix("A", I)); LOOP; // purge M matrices
      m2 = memprobe1; // minus mem 

      if(abs(m1) == abs(m2)) /* does m1 added equal m2 freed? */
         nl(dot(" Ok: no catalog memory leak in " +
            intstr(m1) + " bytes"));
      else (
         nl(dot(" Notice: catalog memory imbalance: " +
            intstr(m1 + m2) + " bytes out of " + 
            intstr(m1) + " bytes")),
         nl(dot(" In linux, small nonzero imbalance is ok"))
      );
   }

   catalog_mem(40); 
