title: Linked List class, how do I access the data of a nested node struct?
body: <p>I'm trying to write this Linked List class for my assignment and I'm trying to write a "for_each" function in the class that gives the user read-only access to the data in each node.  However when I try to access the data in the nodes I get an error saying, "EXC_BAD_ACCESS(code=1, address=0x0)"  How can I get access to my data without leaking memory?  I assume that is what the error is referring to.</p>
  
  <pre><code>#ifndef LINKEDLIST_H
  #define LINKEDLIST_H
  
  #include &lt;iostream&gt;
  #include &lt;memory&gt;
  
  //template&lt;typename T&gt;
  class LinkedList
  {
  private:
  
      struct Node
      {
          int data;
          std::shared_ptr&lt;Node&gt; next;
  
          Node(int d, std::shared_ptr&lt;Node&gt; n)
          :data(d)
          ,next(n)
          {}
          Node()
          {};
      };
  
      std::shared_ptr&lt;Node&gt; head;
      std::shared_ptr&lt;Node&gt; temp;
      std::shared_ptr&lt;Node&gt; current;
  
  public:
  
      LinkedList()
         :head()
      {}
  
      LinkedList(LinkedList&amp; other)
         :head(Clone(other.head))
      {}
  
      std::shared_ptr&lt;Node&gt; getStart()
      {
          return head;
      }
  
      void InsertAt(int value, std::shared_ptr&lt;Node&gt; &amp;n)
      {
          n-&gt;next = std::make_shared&lt;Node&gt;(value, n-&gt;next);
  
      }
  
      void Insertion(int value)
      {
          Insertion(value, head);
      }
  
      void Insertion(int value, std::shared_ptr&lt;Node&gt; &amp;n)
      {
          if (!n)
          {
              InsertAt(value, n);
              return;
          }
  
          if (value &lt; n-&gt;data)
              Insertion(value, n-&gt;next);
          else
              InsertAt(value, n);
      }
  
      void Remove(int value)
      {
          Remove(value, head);
      }
  
      void Remove(int value, std::shared_ptr&lt;Node&gt;&amp; n)
      {
          if (!n) return;
          if (n-&gt;data == value)
          {
              n = n-&gt;next;
              Remove(value, n);
          }
          else
          {
              Remove(value, n-&gt;next);
          }
      }
  
      void for_each(std::shared_ptr&lt;Node&gt; n)
      {
          if(!n) return;
  
          std::cout&lt;&lt;current-&gt;Node::data;  &lt;---- //Here it keeps telling me I have bad_access
          for_each(current-&gt;next);               //"EXC_BAD_ACCESS(code=1, address=0x0)
  
      }
  
      std::shared_ptr&lt;Node&gt; Clone(std::shared_ptr&lt;Node&gt; n) const
      {
          if(!n) return nullptr;
          return std::make_shared&lt;Node&gt;(n-&gt;data, Clone(n-&gt;next));
      }
  
      LinkedList&amp; operator = (const LinkedList&amp; list)
      {
          this-&gt;Clone(list.head);
          return *this;
      }
  };
  
  #endif
  </code></pre>