title: Linked list destructor C++
body: <p>I'm learning to implement Stack using linked list. This is the node class:</p>
  
  <pre><code>class StudentInfo {
      public:
          string id, name, course;
          double GPA;
          StudentInfo *next;
  };
  </code></pre>
  
  <p>This is the Stack class:</p>
  
  <pre><code>class StackLinkedList {
      public:
          StudentInfo* top; //pointer to point to the top node
          int size; //variable to keep the size of the stack
  
      //constructor
      StackLinkedList() {
          this-&gt;size = 0;
          this-&gt;top = NULL;
      }
  
      //destructor
      ~StackLinkedList() {
          StudentInfo *current = top;
          while (top) {
              current = current-&gt;next;
              delete top;
              top = current;
          }
      }
  
      //to add item into stack - push on top
      void push(StudentInfo *newStudent) {
          if (!top) {
              top = newStudent;
              return;
          }
  
          newStudent-&gt;next = top;
          top = newStudent;
          size++;
      }
  
  void main() {
      StudentInfo s1("phi", "123", "computer science", 4.0);
      StudentInfo s2("abc", "123", "software engineer", 4.0);
      StudentInfo s3("zxc", "123", "business management", 4.0);
  
      StackLinkedList list;
      StudentInfo *ptr;
      ptr = &amp;s1;
      list.push(ptr);
      ptr = &amp;s2;
      list.push(ptr);
      ptr = &amp;s3;
      list.push(ptr);
  
  };
  </code></pre>
  
  <p>When I try to run unit test on push() and printAll(), everything is okay. However, after destructor() has been called, and error is showed up Debug Assertion Failed … is_block_type_valid(header-> _block_use). And the debugger triggered a breakpoint at <code>delete top;</code></p>
  
  <pre><code>//destructor
  ~StackLinkedList() {
      StudentInfo *current = top;
      while (top) {
          current = current-&gt;next;
          delete top; //here
          top = current;
      }
  }
  </code></pre>
  
  <p>If I put <code>top = NULL;</code> before <code>delete top;</code>, the error is gone. So, I have a little bit of confusion about the <code>top = NULL;</code> statement.
  Edit: Constructor for NodeType</p>
  
  <pre><code> StudentInfo(string id, string name, string course, double gpa) {
          this-&gt;id = id; this-&gt;name = name; this-&gt;course = course; this-&gt;GPA = gpa; this-&gt;next = NULL;
  }
  </code></pre>