Quantcast
Channel: Forum Pasja Informatyki - Najnowsze pytania i odpowiedzi
Viewing all articles
Browse latest Browse all 83164

Zwalnianie pamięci - Rekurencja

$
0
0

Witam chce poznać opinie kogoś o większym doświadczeniu jeżeli to możliwe czy ten kod poprawnie usuwa "Liste powiązaną" za pomocą rekurencji.

#include <iostream>
#include <cstddef>

using namespace std;

struct Obiekt
{
     int index;
     Obiekt* w_obiekt;
};

Obiekt* DodajNowy(Obiekt* w_lista, int id)
{
     Obiekt* nowyObiekt = new Obiekt;
     nowyObiekt->index = 0;
     nowyObiekt->w_obiekt = w_lista;
     return nowyObiekt;
}

void Usun(Obiekt* w_lista);

int main()
{
     Obiekt* wrog = NULL;

     for(int i=0; i<5; i++)
     {
          wrog = DodajNowy(wrog, i);
     }

     Usun(wrog);

     delete wrog;
     wrog = NULL;

     return 0;
}

void Usun(Obiekt* w_lista)
{
     if(w_lista == NULL){
          return;
     }
     else
          Usun(w_lista->w_obiekt);

     delete w_lista;
     w_lista = NULL;
}

Osobiście wydaje mi się że jest to poprawne rozwiązanie lecz z tą pamięcią nigdy nic nie wiadomo a mój aktualny poziom nie jest w stanie w 100% stwierdzić że to jest rzeczywiście poprawny kod.

Z góry dziękuje za wyświetlenie tego tematu.

Dzień później doszłem do wniosku że ten kod jest zły i stworzyłem taki:

Obiekt* Usun(Obiekt* w_lista);

int main()
{
     Obiekt* wrog = NULL;

     for(int i=0; i<5; i++)
     {
          wrog = DodajNowy(wrog, i);
     }
     wrog = Usun(wrog);

     delete wrog;
     wrog = NULL;

     return 0;
}

Obiekt* Usun(Obiekt* w_lista)
{
     if(w_lista != NULL)
          Usun(w_lista->w_obiekt);

     delete w_lista;
     w_lista = NULL;

     return w_lista;
}

Części której brakuje od góry jest taka sama


Viewing all articles
Browse latest Browse all 83164

Trending Articles