title: Problems clearing a linked list, seg faulting delete
body: <pre><code>template &lt;typename T&gt;
  void LinkedList&lt;T&gt;::clear()
  {
    LinkedList* p = this;
    LinkedList* q = this;
    while(p-&gt;m_next != NULL)
    {
      p = p-&gt;m_next;
      delete q;
      q = p;
    }
    return;
  }
  
  class LinkedList
  {
  public:
    T m_data;                  // Data to be stored
    LinkedList&lt;T&gt;* m_next;     // Pointer to the next element in the list
   //Continues into function declarations.
   // . . .
  };
  </code></pre>
  
  <p>These are the snippets of code I thought relevant, if you need any more let me know. </p>
  
  <p>The problem: I am seg faulting once I hit the line to delete q</p>
  
  <pre><code>delete q;
  </code></pre>
  
  <p>I plugged in some </p>
  
  <pre><code>cerr &lt;&lt; "msg" &lt;&lt; endl;
  </code></pre>
  
  <p>Just to check. Any ideas of how to alter this code to stop the seg fault? Apparently I'm deleting something I shouldn't be, but I can't figure out how. The point of the clear function is to entirely delete the singly linked list except for the ending sentinel. This while loop always seg faults on the first run.</p>
  
  <p>Here is the code testing this. </p>
  
  <pre><code>void test01() {
  
    LinkedList &lt; int &gt; A;
  
    cout &lt;&lt; endl &lt;&lt; endl; 
    cout &lt;&lt; " ***************** " &lt;&lt; endl;
    cout &lt;&lt; " *  TEST SET #1  * " &lt;&lt; endl;
    cout &lt;&lt; " ***************** " &lt;&lt; endl;
  
  
    cout &lt;&lt; "Is the list empty? " &lt;&lt; boolalpha &lt;&lt; A.isEmpty() &lt;&lt;endl; 
    cout &lt;&lt; A &lt;&lt; endl;
    cout &lt;&lt; "Size of A = " &lt;&lt; A.size() &lt;&lt; endl;
  
    //TEST : Inserting 10 numbers to a
    cout &lt;&lt; endl &lt;&lt; "TEST : Inserting 10 numbers to A" &lt;&lt; endl;
    for (int k=0; k&lt;10; k++){
          A.insert_front(k+1);
    } 
    cout &lt;&lt; A &lt;&lt; endl;
    cout &lt;&lt; "Size of a = " &lt;&lt; A.size() &lt;&lt; endl;
  
    //TEST : Clearing A
    cout &lt;&lt; endl &lt;&lt; "TEST : Clearing A" &lt;&lt; endl;
    A.clear();
    cout &lt;&lt; A &lt;&lt; endl;
    cout &lt;&lt; "Size of A = " &lt;&lt; A.size() &lt;&lt; endl &lt;&lt; endl;
  
  
    cout &lt;&lt; "Test 01 - Done!" &lt;&lt; endl;
  } // Destructor Called Here!!
  </code></pre>
  
  <p>I simply changed the function to</p>
  
  <pre><code>template &lt;typename T&gt;
  void LinkedList&lt;T&gt;::clear()
  {
    LinkedList* p = this;
    LinkedList* q = this;
    if(p-&gt;m_next != NULL)
    {
      p = p-&gt;m_next;
      q = q-&gt;m_next;
    }
    while(p-&gt;m_next != NULL)
    {
      q = p;
      p = p-&gt;m_next;
      delete q;
    }
    m_next = NULL;
    return;
  }
  </code></pre>
  
  <p>Works now.</p>