home *** CD-ROM | disk | FTP | other *** search
/ C!T ROM 2 / ctrom_ii_b.zip / ctrom_ii_b / PROGRAM / C / AETSK101 / MEMLEAK.CC < prev    next >
C/C++ Source or Header  |  1991-12-02  |  1KB  |  76 lines

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. #define NO_LEAK 0
  6.  
  7. template <class T> class Q {
  8. private:
  9.     int hd, tl, cnt, max;
  10.     T   *a;
  11. public:
  12.     Q(int n=10) { hd = tl = 0; cnt = 0; max = n; a = new T [n]; }
  13.     ~Q() { delete [] a; }
  14.     int add(T);
  15.     int del(T&);
  16. };
  17.  
  18. template <class T> int Q<T>::add(T t)
  19. {
  20.     if (cnt == max)
  21.         return 0;
  22. #if NO_LEAK
  23.     a[ tl ].T::~T();
  24. #endif
  25.     a[ tl++ ] = t;
  26.     if (tl == max)
  27.         tl = 0;
  28.     cnt++;
  29.     return 1;
  30. }
  31.  
  32. template <class T> int Q<T>::del(T& t)
  33. {
  34.     if (!cnt)
  35.         return 0;
  36. #if NO_LEAK
  37.     t.T::~T();
  38. #endif
  39.     t = a[ hd++ ];
  40.     if (hd == max)
  41.         hd = 0;
  42.     cnt--;
  43.     return 1;
  44. }
  45.  
  46.  
  47. class MemEater {
  48. private:
  49.     char *junk;
  50. public:
  51.     MemEater() { printf("():allocating\n"); junk = new char [ 10000 ];
  52.         if (!junk) exit(1); }
  53.     ~MemEater() { printf("deleting\n"); delete junk; }
  54.     MemEater &operator=(MemEater &me)
  55.         { printf("op=:allocating\n"); junk = new char [ 10000 ]; 
  56.         if (!junk) exit(2); memcpy(junk, me.junk, 10000); return *this; }
  57.     MemEater(MemEater &me)
  58.         { printf("copying..."); *this=me; }
  59.         
  60. };
  61.  
  62. Q<MemEater> qme(10);
  63.  
  64. void main(void)
  65. {
  66.     MemEater m;
  67.  
  68.     for (int i = 0; i < 320; i++) {
  69.         printf("i = %d\n", i);
  70.         printf("adding\n");
  71.         qme.add(m);
  72.         printf("getting\n");
  73.         qme.del(m);
  74.     }
  75. }
  76.