As computing becomes more ubiquitous in our objects, designers need to be more aware of how to design meaningful interactions into electronically enhanced objects. At the University of Washington, a class of junior Interaction Design majors is exploring this question. These pages chronicle their efforts.

Thursday, June 6, 2013

C++ Memory dump error resolved, Custom Queue class — Mallika Simone, Sarah Churng

For a while, we were struggling with a memory dump problem whenever we used the QueueArray structures in our code. About 2 weeks ago, we fixed them. In C++, when you pass an object as a function argument in C, it makes a copy of the object, instead of just calling it in reference. Which is fine for chars and ints and whatnot small objects. But since the built-in garbage collection will throw away that instance every call you make, it ends up building a new copy every single time you call the function*.

The fix: Use '&' in your calls to reference the object, rather than copy it. Here's our function getAverage, which returns the average of the contents of a QueueArray:

// Get Average of the contents of a queue of ints:
int getAverage(QueueArray <int>& qa){                    
  int sum = 0;                //the summation of values
  int cnt = qa.count();       //the count of distinct values
  
  while ( !qa.isEmpty() ) {
    sum = sum + qa.pop();
  }
  
  return ( sum / cnt );       //return the mean average 
}


Also, here's an override of QueueArrays, called Queue, which we are using because it has custom functions for our drunk-detection purposes:

class QueueNode {
  public:
    QueueNode(int val, QueueNode* next)
    {
     _val = val;
     _next = next;
    } 
    
    int _val;
    QueueNode* _next;
};


class Queue {
    public:
      Queue() {
        head = NULL; 
      }
      
      void Append(int val) {
        QueueNode* qn = new QueueNode(val, head);
        head = qn;
      };
      
      void Clear()       {
        QueueNode* cur = head;
        head = NULL;
        while (cur != NULL)
        {
         QueueNode* next = cur->_next;
         delete cur;
         cur = next;
        }
      }
      
      float Average() {
        int cnt = 0;
        int sum = 0;
        QueueNode* cur = head;

        while (cur != NULL) {
          cnt++;
          sum += cur->_val;
          cur = cur->_next;
        }
        
        if (cnt == 0)
          return 0.0;
        else
          return (float)sum/(float)cnt;
      }
    private:
      QueueNode* head;
};

No comments:

Post a Comment