title: Memory leak on a "return new node" and i can't find a way to fix it
body: <p>Got a problem with a function that returns a "new node" and I can't find it. Here's the function:</p>
  
  <pre><code>node* append_new_node(node* l, const T&amp; tt) {
      if (l == 0)
          return new node(0, tt);
  
      node* n = l;
      while (n-&gt;next != 0) {
          if (cmp(n-&gt;key, tt)) {
              int a= n-&gt;counter;
              a++;
              n-&gt;counter=a;
  
              n=0;
              delete n;
              return 0;
          }
          else {
              n = n-&gt;next;
          }
      }
  
      //check per evitare ripetizioni fra numeri uguali consecutivi
      if (!cmp(n-&gt;key, tt)){
          n-&gt;next = new node(0, tt);
      }
      else {
          n-&gt;counter = n-&gt;counter+1;
          n=0;
          delete n;
          return 0;
      }
      n=0;
      delete n;
      return l;
  }
  </code></pre>
  
  <p>valgrind report:</p>
  
  <pre><code>==2481== HEAP SUMMARY:
  ==2481==     in use at exit: 480 bytes in 16 blocks
  ==2481==   total heap usage: 81 allocs, 65 frees, 2,440 bytes allocated
  ==2481== 
  ==2481== Searching for pointers to 16 not-freed blocks
  ==2481== Checked 193,240 bytes
  ==2481== 
  ==2481== 96 (32 direct, 64 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 10
  ==2481==    at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==2481==    by 0x404039: huffman&lt;Color, CaseInsensitiveCmp&gt;::append_new_node(huffman&lt;Color, CaseInsensitiveCmp&gt;::node*, Color const&amp;) (huffman.h:311)
  ==2481==    by 0x402D61: huffman&lt;Color, CaseInsensitiveCmp&gt;::node* huffman&lt;Color, CaseInsensitiveCmp&gt;::build_list&lt;std::_List_iterator&lt;Color&gt; &gt;(std::_List_iterator&lt;Color&gt;, std::_List_iterator&lt;Color&gt;, unsigned int&amp;) (huffman.h:344)
  ==2481==    by 0x402283: huffman&lt;Color, CaseInsensitiveCmp&gt;::huffman&lt;std::_List_iterator&lt;Color&gt; &gt;(std::_List_iterator&lt;Color&gt;, std::_List_iterator&lt;Color&gt;) (huffman.h:103)
  ==2481==    by 0x4016F5: do_test() (main.cpp:137)
  ==2481==    by 0x401BCB: main (main.cpp:192)
  ==2481== 
  ==2481== 96 (32 direct, 64 indirect) bytes in 1 blocks are definitely lost in loss record 7 of 10
  ==2481==    at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==2481==    by 0x404039: huffman&lt;Color, CaseInsensitiveCmp&gt;::append_new_node(huffman&lt;Color, CaseInsensitiveCmp&gt;::node*, Color const&amp;) (huffman.h:311)
  ==2481==    by 0x402D61: huffman&lt;Color, CaseInsensitiveCmp&gt;::node* huffman&lt;Color, CaseInsensitiveCmp&gt;::build_list&lt;std::_List_iterator&lt;Color&gt; &gt;(std::_List_iterator&lt;Color&gt;, std::_List_iterator&lt;Color&gt;, unsigned int&amp;) (huffman.h:344)
  ==2481==    by 0x402389: void huffman&lt;Color, CaseInsensitiveCmp&gt;::reset&lt;std::_List_iterator&lt;Color&gt; &gt;(std::_List_iterator&lt;Color&gt;, std::_List_iterator&lt;Color&gt;) (huffman.h:112)
  ==2481==    by 0x40186F: do_test() (main.cpp:151)
  ==2481==    by 0x401BCB: main (main.cpp:192)
  ==2481== 
  ==2481== 96 (32 direct, 64 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 10
  ==2481==    at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==2481==    by 0x404039: huffman&lt;Color, CaseInsensitiveCmp&gt;::append_new_node(huffman&lt;Color, CaseInsensitiveCmp&gt;::node*, Color const&amp;) (huffman.h:311)
  ==2481==    by 0x403363: huffman&lt;Color, CaseInsensitiveCmp&gt;::node* huffman&lt;Color, CaseInsensitiveCmp&gt;::build_list&lt;huffman&lt;Color, CaseInsensitiveCmp&gt;::const_iterator&gt;(huffman&lt;Color, CaseInsensitiveCmp&gt;::const_iterator, huffman&lt;Color, CaseInsensitiveCmp&gt;::const_iterator, unsigned int&amp;) (huffman.h:344)
  ==2481==    by 0x4023F4: huffman&lt;Color, CaseInsensitiveCmp&gt;::huffman(huffman&lt;Color, CaseInsensitiveCmp&gt; const&amp;) (huffman.h:86)
  ==2481==    by 0x401936: do_test() (main.cpp:159)
  ==2481==    by 0x401BCB: main (main.cpp:192)
  ==2481== 
  ==2481== 96 (32 direct, 64 indirect) bytes in 1 blocks are definitely lost in loss record 9 of 10
  ==2481==    at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==2481==    by 0x404039: huffman&lt;Color, CaseInsensitiveCmp&gt;::append_new_node(huffman&lt;Color, CaseInsensitiveCmp&gt;::node*, Color const&amp;) (huffman.h:311)
  ==2481==    by 0x403363: huffman&lt;Color, CaseInsensitiveCmp&gt;::node* huffman&lt;Color, CaseInsensitiveCmp&gt;::build_list&lt;huffman&lt;Color, CaseInsensitiveCmp&gt;::const_iterator&gt;(huffman&lt;Color, CaseInsensitiveCmp&gt;::const_iterator, huffman&lt;Color, CaseInsensitiveCmp&gt;::const_iterator, unsigned int&amp;) (huffman.h:344)
  ==2481==    by 0x4023F4: huffman&lt;Color, CaseInsensitiveCmp&gt;::huffman(huffman&lt;Color, CaseInsensitiveCmp&gt; const&amp;) (huffman.h:86)
  ==2481==    by 0x4024B7: huffman&lt;Color, CaseInsensitiveCmp&gt;::operator=(huffman&lt;Color, CaseInsensitiveCmp&gt; const&amp;) (huffman.h:135)
  ==2481==    by 0x401AEC: do_test() (main.cpp:183)
  ==2481==    by 0x401BCB: main (main.cpp:192)
  ==2481== 
  ==2481== 96 (24 direct, 72 indirect) bytes in 1 blocks are definitely lost in loss record 10 of 10
  ==2481==    at 0x4C2B0E0: operator new(unsigned long) (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
  ==2481==    by 0x40398D: huffman&lt;int, IntCmp&gt;::append_new_node(huffman&lt;int, IntCmp&gt;::node*, int const&amp;) (huffman.h:311)
  ==2481==    by 0x402687: huffman&lt;int, IntCmp&gt;::node* huffman&lt;int, IntCmp&gt;::build_list&lt;std::_List_iterator&lt;int&gt; &gt;(std::_List_iterator&lt;int&gt;, std::_List_iterator&lt;int&gt;, unsigned int&amp;) (huffman.h:344)
  ==2481==    by 0x402021: huffman&lt;int, IntCmp&gt;::huffman&lt;std::_List_iterator&lt;int&gt; &gt;(std::_List_iterator&lt;int&gt;, std::_List_iterator&lt;int&gt;) (huffman.h:103)
  ==2481==    by 0x40151A: dotest_iterators() (main.cpp:113)
  ==2481==    by 0x401BD0: main (main.cpp:193)
  ==2481== 
  ==2481== LEAK SUMMARY:
  ==2481==    definitely lost: 152 bytes in 5 blocks
  ==2481==    indirectly lost: 328 bytes in 11 blocks
  ==2481==      possibly lost: 0 bytes in 0 blocks
  ==2481==    still reachable: 0 bytes in 0 blocks
  ==2481==         suppressed: 0 bytes in 0 blocks
  ==2481== 
  ==2481== ERROR SUMMARY: 5 errors from 5 contexts (suppressed: 0 from 0)
  ==2481== ERROR SUMMARY: 5 errors from 5 contexts (suppressed: 0 from 0)
  samu@Samu-MS-7821:~/Desktop/test$ 
  </code></pre>
  
  <p>I'll copy now also other classes named by valgrind</p>
  
  <pre><code>  template &lt;typename InIter&gt;
  node* build_list(InIter from, InIter to, unsigned int&amp; sz){
  unsigned int n = 0;
  node* h = 0;
  while (from != to) {
    node* tmp;
    try {
  
  tmp = append_new_node(h, *from);
  
    } catch(...) {
  free_nodes(h);
  throw;
    }
    if (tmp != 0) {
  ++n;
  h = tmp;
    }
    ++from;
    tmp=0;
    delete tmp;
  }
  sz = n;
  
  //creo un array di frequenze
  int frequenze[sz];
  node* scor=h;
  int i=0;
  while(scor!=0){
      int prova=scor-&gt;counter;
      frequenze[i]=prova;
      i++;
      scor=scor-&gt;next;
  }
  
  
  
  //ordino array
  insertion_sort(frequenze,sz);
  
  
  //creo lista ordinata+assegno codifica
  node* coded = 0;
  string endcode="1";
  string midcode="\n";
  string code;
  for(int q=sz-1;q&gt;=0;q--){
          node* temp;
          code=(midcode+endcode);
           try {
              temp = append_new_node_c(coded, find_freq(h,frequenze[q]), code);
              //std::cout&lt;&lt;frequenze[q]&lt;&lt;"\n";
          } catch(...) {
              free_nodes(h);
              throw;
          }
          coded=temp;
          if(q-1&lt;=0){
              endcode="0";
          }
          else{
              midcode=midcode+"0";
          }
  
  }
  
  h=0;
  scor=0;
  delete h;
  delete scor;
  
  return coded;}
  </code></pre>
  
  <p>another function</p>
  
  <pre><code>huffman(const huffman&amp; v)
  : head(0), sz(0), cmp(v.cmp){
  head = build_list(v.begin(), v.end(), sz);}
  </code></pre>
  
  <p>Really guys, it would be awesome if someone could help me. I cant really find whhat i have to free or delete to prevent this memory leak.
  I dont copy all the code cause is about 300 line, but if you need it i will.</p>
  
  <p>Here is the main</p>
  
  <pre><code>int main(){ 
  try {
  do_test();
  dotest_iterators();
  std::cout &lt;&lt; "ok\n";} 
  catch (std::exception&amp; e){
  std::cerr &lt;&lt; e.what() &lt;&lt; std::endl;}
  return 0;}
  
  class Color{
  public:
  Color(int r, int g, int b): red(r), green(g), blue(b){}
  
  void print(std::ostream&amp; os) const{
  os &lt;&lt; "Color("
     &lt;&lt; red &lt;&lt; ", "
     &lt;&lt; green &lt;&lt; ", "
     &lt;&lt; blue &lt;&lt; ")";}
  
  bool operator==(const Color&amp; c) const {
  return red == c.red &amp;&amp; green == c.green &amp;&amp; blue == c.blue;}
  
  bool operator!=(const Color&amp; c) const {
  return !operator==(c);
  }
  
  private:
  int red;
  int green;
  int blue;
  };
  
  
  /* Stampa un'istanza di Color. */
  std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os,
           const Color&amp; c){
  c.print(os);
  return os;}
  
  
  struct CaseInsensitiveCmp{
  
  bool operator()(const Color&amp; a, const Color&amp; b) const{
  return a==b;}
  };
  
  
  struct IntCmp{
  
  bool operator()(const int&amp; a, const int&amp; b) const{
  return a==b;
  }
  };
  
  
  
  void dotest_iterators(){
  
  typedef IntCmp IntCompare;
  
  std::list&lt;int&gt; lista;
  int a,b,c,d,e,f,g,h;
  a=1;
  b=2;
  c=2;
  d=1;
  e=1;
  f=7;
  g=1;
  h=6;
  
  lista.push_front(a);
  lista.push_front(b);
  lista.push_front(c);
  lista.push_front(d);
  lista.push_front(e);
  lista.push_front(f);
  lista.push_front(g);
  lista.push_front(h);
  
  //test sul codice
  //std::equal_to&lt;int&gt;
  
  huffman&lt;int, IntCompare &gt; codHuff(lista.begin(),lista.end());
  //std::cout &lt;&lt; codHuff.size() &lt;&lt; "\n";
  assert(codHuff.size()==4);
  
  //test valori di codifica
  codHuff.find(1);
  codHuff.find(2);
  codHuff.find(6);
  codHuff.find(7);}
  
  void do_test(){
  
  typedef CaseInsensitiveCmp ColorCompare;
  
  std::list&lt;Color&gt; lista2;
  //creazione lista e test funzione stampa e size
  lista2.push_front(Color(255, 0, 0));
  lista2.push_front(Color(0, 255, 0));
  lista2.push_front(Color(0, 0, 255));
  lista2.push_front(Color(255, 0, 0));
  
  huffman&lt;Color, ColorCompare &gt; codHuff2(lista2.begin(),lista2.end());
  assert(codHuff2.size()==3);
  
  codHuff2.find(Color(255, 0, 0));
  codHuff2.find(Color(0, 255, 0));
  codHuff2.find(Color(0, 0, 255));
  
  std::list&lt;Color&gt; lista3;
  
  lista3.push_front(Color(0, 255, 0));
  lista3.push_front(Color(0, 0, 255));
  lista3.push_front(Color(255, 0, 0));
  
  //funzione reset
  codHuff2.reset(lista3.begin(),lista3.end());
  assert(codHuff2.size()==3);
  
  codHuff2.find(Color(255, 0, 0));
  codHuff2.find(Color(0, 255, 0));
  codHuff2.find(Color(0, 0, 255));
  
  //copy constructor
  huffman&lt;Color, ColorCompare &gt; codHuff3(codHuff2);
  assert(codHuff2.size() == codHuff3.size());
  
  codHuff3.find(Color(255, 0, 0));
  codHuff3.find(Color(0, 255, 0));
  codHuff3.find(Color(0, 0, 255));
  
  
  try {
  codHuff2.find(Color(0, 3, 255));
  assert(0);
  } catch(element_not_found&amp;) {
  }
  
  //clear
  codHuff3.clear();
  assert(codHuff3.size()==0);
  
  //swap
  codHuff2.swap(codHuff3);
  assert(codHuff2.size()==0);
  assert(codHuff3.size()==3);
  
  //assegnamento
  codHuff2=codHuff3;
  assert(codHuff2.size()==3);}
  </code></pre>
  
  <p>I hope u guys can help me</p>
  
  <p>Update: I'll put the all code right here:</p>
  
  <pre><code>#ifndef fuffman_h
  
  #include &lt;stdexcept&gt;
  #include &lt;iterator&gt;
  #include &lt;cassert&gt;
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  #include &lt;exception&gt;
  
   using namespace std;
  /** Versione 2: introduzione degli iteratori. */
  
  
  
  /**
   * Eccezione lanciata quando si cerca di inserire una chiave gia'
   * presente.
   */
  struct duplicated_element : std::runtime_error
  {
    duplicated_element() : std::runtime_error("Duplicated Element") { }
  };
  
  /**
   * Eccezione lanciata quando nussuna delle coppie memorizzate
   * corrisponde alla chiave rischiesta.
   */
  struct element_not_found : std::runtime_error
  {
    element_not_found() : std::runtime_error("Element not found") { }
  };
  
  
  /**
   * Struttura contenente le coppie chiave/valore. NON NECESSARIA?
   */
  
   /*
  template &lt;typename K, typename T&gt;
  struct key_value_pair
  {
    key_value_pair(const K&amp; kk, const T&amp; vv) : key(kk), value(vv) { }
  
    template &lt;typename K1, typename T1&gt;
    key_value_pair(const key_value_pair&lt;K1, T1&gt;&amp; p) : key(p.key), value(p.value) { }
  
    K key;
    T value;
  };
  */
  
  
  /**
   * Un vettore associativo.
   *
   * Contiene coppie chiave/valore di tipo K e T, rispettivamente. Non
   * e' possibile inserire piu' coppie con chiave equivalenti.
   * L'equivalenza tra le chiavi e' definita tramite un funtore
   * specificato dall'utente.
   */
  template &lt;typename T, typename Cmp&gt;
  class huffman
  {
  public:
  
  //  typedef key_value_pair&lt;K, T&gt; pair;
  
    /**
     * Costruttore di default.
     *
     * Il vettore associativo risultante e' vuoto.
     */
    huffman() : head(0), sz(0), cmp() { }
  
    explicit huffman(const Cmp&amp; c) : head(0), sz(0), cmp(c) { }
  
    /**
     * Copy constructor.
     *
     * In questa versione l'ordine interno delle copie memorizzate
     * risulta invertito.
     */
    huffman(const huffman&amp; v)
      : head(0), sz(0), cmp(v.cmp)
    {
      head = build_list(v.begin(), v.end(), sz);
    }
  
  
    template&lt;typename T1, typename Cmp1&gt;
    huffman(const huffman&lt;T1, Cmp1&gt;&amp; v)
      : head(0), sz(0), cmp()
    {
      head = build_list(v.begin(), v.end(), sz);
    }
  
  
    //La funzione prende in ingresso due iteratori puntanti a inizio e fine di una lista e ne creano l'array
    template &lt;typename InIter&gt;
    huffman(InIter from, InIter to)
      : head(0), sz(0), cmp()
    {
      head = build_list(from, to, sz);    
    }
  
    template &lt;typename InIter&gt;
    void reset(InIter from, InIter to)
      //: head(0), sz(0), cmp()
    {
      if(head!=0){
      clear();}
      head = build_list(from, to, sz);    
    }
  
    template &lt;typename InIter&gt;
    huffman(InIter from, InIter to, const Cmp&amp; c)
      : head(0), sz(0), cmp(c)
    {
      head = build_list(from, to, sz);    
    }
  
    /**
     * Distruttore.
     */
    ~huffman()
    {
      free_nodes(head);
    }
  
    /**
     * Operatore di assegnamento.
     */
    huffman&amp; operator=(const huffman&amp; v)
    {
      huffman tmp(v);
      swap(tmp);
      return *this;
    }
  
    template&lt;typename T1, typename Cmp1&gt;
    huffman&amp; operator=(const huffman&lt;T1, Cmp1&gt;&amp; v)
    {
      huffman tmp(v);
      swap(tmp);
      return *this;
    }
  
  
  
    //???
  
    /*
    template &lt;typename InIter&gt;
    void assign(InIter from, InIter to)
    {
      huffman tmp(from, to);
      swap(tmp);
    }
      */
  
  
    /**
     * Inserisce una nuova coppia nel vettore.
     *
     * Lancia l'eccezione duplicated_element Nel caso in cui la chiave sia
     * gia' presente.
     */
  
     //E'  UTILE AI FINI DEL PROGETTO? ELEIMINARE O SPOSTARE IN PRIVATE?
     //PER ORA LA TOLGO
  
    /*
    void insert(const T&amp; t)
    {
      node* r = append_new_node(head, t);
      if (r == 0)
        throw duplicated_element();
      head = r;
      ++sz;
    }
    */
  
    /**
     *Stampa codifica, dato un elemento.
     *
     * Lancia l'eccezione element_not_found se nessun elemento corrisponde
     * alla chiave specificata.
     */
  
  
    void find(const T&amp; t)
    {
      node* n = find_code(head, t);
      if (n == 0)
        throw element_not_found();
      n=0;
      delete n;
    }
  
  
    /**
     * Rimuove la coppia corrispondente alla chiave specificata.
     *
     * Lancia l'eccezione element_not_found se nessun elemento corrisponde
     * alla chiave specificata.
     */
  
  
     //E' UTILE AI FINI DEL PROGETTO? ELIMINARE O SPOSTARE IN PRIVATE???
     //PER ORA LA TOLGO
  
    /*
    void erase(const T&amp; t)
    {
      node* n = find_node(head, t);
      if (n == 0)
        throw element_not_found();
      --sz;
      head = erase_node(head, n);
    }
    */
  
    /**
     * Restituisce il numero di coppie memorizzate.
     */
    unsigned int size() const
    {
      return sz;
    }
  
    /**
     * Svuota il vettore associativo.
     */
    void clear()
    {
      huffman tmp;
      swap(tmp);
    }
  
    /**
     * Scambia il contenuto di due vettori associativi.
     */
    void swap(huffman&amp; v) {
      node* tmp = head; head = v.head; v.head = tmp;
      unsigned int tmps = sz;
      sz = v.sz;
      v.sz = tmps;
      Cmp tmpc = cmp;
      cmp = v.cmp;
      v.cmp = tmpc;
    }
  
  private:
  
    // L'implementazione si basa su una lista a link singolo.  
  
    struct node {
      node(node* n, const T&amp; tt) : key(tt), counter(1), codifica(""), next(n){ }
      node(node* n, const T&amp; tt, string c) : key(tt), counter(0), codifica(c), next(n){ }
      T key;
      int counter;
      string codifica;
      node* next;
    };
  
  
    node* head;  // Puntatore alla testa della lista
    unsigned int sz;  // Numero di coppie memorizzate
    Cmp cmp;  // funtore di confronto tra chiavi
  
  
    // Inserisce p in testa alla lista l. Restituisce il nuovo nodo. MI SERVE?
    node* insert_node(node* l, const T&amp; tt)
    {
      node* ret = new node(l, tt);
      return ret;
    }
  
    //Appendo con codifica
      node* append_new_node_c(node* l, const T&amp; tt, string c)
    {
      if (l == 0)
        return new node(0, tt, c);
  
      node* n = l;
      while (n-&gt;next != 0) {
        if (cmp(n-&gt;key, tt)) {
          int a= n-&gt;counter;
          a++;
          n-&gt;counter=a;
        n=0;
        delete n;
      return 0;}
      else{
        n = n-&gt;next;
        }
      }
  
      //check per evitare ripetizioni fra numeri uguali consecutivi
      if (!cmp(n-&gt;key, tt)){
      n-&gt;next = new node(0, tt, c);}
      else{
      n-&gt;counter=n-&gt;counter+1;
      n=0;
      delete n;
      return 0;}
      n=0;
      delete n;
      return l;
    }
  
  
    // Append
    node* append_new_node(node* l, const T&amp; tt)
    {
      if (l == 0)
        return new node(0, tt);
  
      node* n = l;
      while (n-&gt;next != 0) {
        if (cmp(n-&gt;key, tt)) {
          int a= n-&gt;counter;
          a++;
          n-&gt;counter=a;
      n=0;
      delete n;
      return 0;}
      else{
        n = n-&gt;next;
        }
      }
  
      //check per evitare ripetizioni fra numeri uguali consecutivi
      if (!cmp(n-&gt;key, tt)){
      n-&gt;next = new node(0, tt);}
      else{
      n-&gt;counter=n-&gt;counter+1;
      n=0;
      delete n;
      return 0;}
      n=0;
      delete n;
      return l;
    }
  
  
    //implementa qua merge e codifica
    template &lt;typename InIter&gt;
    node* build_list(InIter from, InIter to, unsigned int&amp; sz)
    {
      unsigned int n = 0;
      node* h = 0;
      while (from != to) {
        node* tmp;
        try {
  
      tmp = append_new_node(h, *from);
  
        } catch(...) {
      free_nodes(h);
      throw;
        }
        if (tmp != 0) {
      ++n;
      h = tmp;
        }
        ++from;
      tmp=0;
      delete tmp;
      }
      sz = n;
  
      //creo un array di frequenze
      int frequenze[sz];
      node* scor=h;
      int i=0;
      while(scor!=0){
          int prova=scor-&gt;counter;
          frequenze[i]=prova;
          i++;
          scor=scor-&gt;next;
      }
  
  
  
      //ordino array
      insertion_sort(frequenze,sz);
  
  
      //creo lista ordinata+assegno codifica
      node* coded = 0;
      string endcode="1";
      string midcode="\n";
      string code;
      for(int q=sz-1;q&gt;=0;q--){
              node* temp;
              code=(midcode+endcode);
               try {
                  temp = append_new_node_c(coded, find_freq(h,frequenze[q]), code);
                  //std::cout&lt;&lt;frequenze[q]&lt;&lt;"\n";
              } catch(...) {
                  free_nodes(coded);
                  throw;
              }
              coded=temp;
              temp=0;
              delete temp;
              if(q-1&lt;=0){
                  endcode="0";
              }
              else{
                  midcode=midcode+"0";
              }
  
      }
  
      h=0;
      scor=0;
      delete h;
      delete scor;
      return coded;
    }
  
      //trovo i T dalle frequenze
     T find_freq(node* l, const int f)
    {
      while (l != 0) {
        if (l-&gt;counter==f){
        //resetto il counter affinchè non venga ricercato in seguito
        l-&gt;counter=0;
      return l-&gt;key;}
        l = l-&gt;next;
      }
      //return 0;
    }
  
    const T find_freq(const node* l, const int f) const
    {
      while (l != 0) {
        if (l-&gt;counter==f){
          l-&gt;counter=0;
      return l-&gt;key;}
        l = l-&gt;next;
      }
      //return 0; //SERIO PROBLEMA AL RIGUARDO DI CIO PER LE CLASSI/COSTRUTTI che a quanto pare viene risolto restituendo un fico secco
    }
  
    //STAMPA DELLA CODIFICA
  
     node* find_code(node* l, const T&amp; t)
    {
      while (l != 0) {
        if (cmp(l-&gt;key, t)){
        std::cout &lt;&lt; l-&gt;codifica&lt;&lt;" codifica \n";
      return l;}
        l = l-&gt;next;
      }
      return 0;
    }
  
    const node* find_code(const node* l, const T&amp; t) const
    {
      while (l != 0) {
        if (cmp(l-&gt;key, t)){
        std::cout &lt;&lt; l.codifica;
      return l;}
        l = l-&gt;next;
      }
      return 0;
    }
  
  
    // Cerca k nella lista l. Restituisce il nodo corrispondente, o null
    // se la chiave non viene trovata.
    node* find_node(node* l, const T&amp; t)
    {
      while (l != 0) {
        if (cmp(l-&gt;key, t))
      return l;
        l = l-&gt;next;
      }
      return 0;
    }
  
    const node* find_node(const node* l, const T&amp; t) const
    {
      while (l != 0) {
        if (cmp(l-&gt;key, t))
      return l;
        l = l-&gt;next;
      }
      return 0;
    }
  
    /// Toglie n da l
    node* erase_node(node* l, node* n)
    {
      node* h = l;
  
      if (l == n) {
        l = l-&gt;next;
        delete n;
        return l;
      }    
  
      while (l != 0 &amp;&amp; l-&gt;next != n) {
        l = l-&gt;next;
      }
      if (l == 0)
        return h;
  
      l-&gt;next = n-&gt;next;
      delete n;
  
      return h;
    }
  
    void free_nodes(node* l)
    {
      while (l != 0) {
        node* tmp = l;
        l = l-&gt;next;
        delete tmp;
      }
    }
  
    void insertion_sort(int arr[], int length) {
      int i, j ,tmp;
      for (i = 1; i &lt; length; i++) {
          j = i;
          while (j &gt; 0 &amp;&amp; arr[j - 1] &gt; arr[j]) {
              tmp = arr[j];
              arr[j] = arr[j - 1];
              arr[j - 1] = tmp;
              j--;
          }
      }
   }
  
  public:
  
  
    class iterator
    {
    public:
      typedef T value_type;
      typedef int distance_type;
      typedef T* pointer;
      typedef T&amp; reference;
      typedef std::forward_iterator_tag iterator_category;
  
      iterator() : n(0) {}
  
      // iterator(const iterator&amp; it);
      // iterator&amp; operator=(const iterator&amp; it);
  
      iterator&amp; operator++()
      {
        assert(n != 0);
        n = n-&gt;next;
        return *this;
      }
  
      iterator operator++(int)
      {
        iterator tmp = *this;
        operator++();
        return tmp;
      }
  
      reference operator*() const
      {
        assert(n != 0);
        return n-&gt;key;
      }
  
      pointer operator-&gt;() const
      {
        assert(n != 0);
        return &amp;(n-&gt;key);
      }
  
    private:
      explicit iterator(node* nn) : n(nn) { }
  
      node* n;
  
      friend class huffman;
      friend bool operator==(const iterator&amp; a, const iterator&amp; b)
      {
        return a.n == b.n;
      }
  
      friend bool operator!=(const iterator&amp; a, const iterator&amp; b)
      {
        return !(a == b);
      }
    };
  
    class const_iterator
    {
    public:
      typedef const T value_type;
      typedef int distance_type;
      typedef const T* pointer;
      typedef const T&amp; reference;
      typedef std::forward_iterator_tag iterator_category;
  
      const_iterator() : n(0) {}
  
      const_iterator(const iterator&amp; it) : n (it.n) { }
  
      const_iterator&amp; operator=(const iterator&amp; it)
      {
        n = it.n;
        return *this;
      }
  
      const_iterator&amp; operator++()
      {
        assert(n != 0);
        n = n-&gt;next;
        return *this;
      }
  
      const_iterator operator++(int)
      {
        const_iterator tmp = *this;
        operator++();
        return tmp;
      }
  
      reference operator*() const
      {
        assert(n != 0);
        return n-&gt;key;
      }
  
      pointer operator-&gt;() const
      {
        assert(n != 0);
        return &amp;(n-&gt;key);
      }
  
    private:
      explicit const_iterator(node* nn) : n(nn) { }
  
      const node* n;
  
      friend class huffman;
      friend bool operator==(const const_iterator&amp; a, const const_iterator&amp; b)
      {
        return a.n == b.n;
      }
  
      friend bool operator!=(const const_iterator&amp; a, const const_iterator&amp; b)
      {
        return !(a == b);
      }
  
    };
  
  
    iterator begin() { return iterator(head); }
    iterator end() { return iterator(0); }
    const_iterator begin() const { return const_iterator(head); }
    const_iterator end() const { return const_iterator(0); }
  
    iterator finditer(const T&amp; t)
    {
      return iterator(find_node(head, t));
    }
  
    const_iterator finditer(const T&amp; t) const
    {
      return const_iterator(find_node(head, t));
    }
  };
  
  
  
  #endif
  </code></pre>