Question

Its my first classs

class Wiersz
    {
    private:
        char *zawartosc;
    public:
        Wiersz():zawartosc(NULL){}
        Wiersz(const char *z)
        {
            this->zawartosc = new char[strlen(z) + 1];
            strcpy_s(this->zawartosc, (strlen(z) + 1) * sizeof(char) , z);

            zawartosc[strlen(z) ] = '\0';
        }
        void usun()
        {
            delete [] zawartosc;
        }
        ~Wiersz()
        {
            usun();
        }

    };

its my structure to second class

struct El_tekst
{
    Wiersz *wiersz;
    El_tekst *next;
    El_tekst():next(NULL),wiersz(NULL){}
};

its my second class

 class Tekst
    {
    protected:
        El_tekst *tekst;
    public:
        Tekst(): tekst(NULL){}
         ~Tekst()
        {
            El_tekst *_rob;
            while(this->tekst != NULL)
            {
                _rob = this->tekst;
                this->tekst = this->tekst->next;

                _rob->wiersz->usun();
                delete _rob;
            }
        }

        Tekst & operator<<(const char *dod_tekst)
        {

            if(this->tekst == NULL)
            {
                this->tekst = new El_tekst();
                this->tekst->wiersz = new Wiersz(dod_tekst);
            }
            else
            {
                El_tekst *_rob = this->tekst;
                while(_rob->next != NULL)
                {
                    _rob = _rob->next;
                }
                (_rob->next) = new El_tekst();
                (_rob->next)->wiersz = new Wiersz(dod_tekst);
            }
            return *this;
        }
    };

this is the 3th class

class Edytor_tekstu : public Tekst
{
private:
    int numer_aktualnego_wiersza;
public:
    Edytor_tekstu():numer_aktualnego_wiersza(0){}
    ~Edytor_tekstu(){}
};

and now the main function:

void main()
{
    Edytor_tekstu b;

    b<<"ala";
}

There is 4 bytes of dumb memory, where do i make mistake? Propably i allcoate something what shoudnt be, or my destructors are really bad.

Was it helpful?

Solution

Rather then using _rob->wiersz->usun(); use delete _rob->weirz; which will also automatically call usun(). Calling the first one deletes some of the data contained by wiersz, but not wiersz itself which contains exactly one 4-byte pointer. If you include both lines, you'll try to delete the memory that wiersz allocated twice which should cause an error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top