Как мога да предотвратя изтичане на памет в моята C++ програма?

Работя върху програма, която използва реализация на двойно свързан списък на сортирана опашка. Този файл е единственият файл, при който възниква изтичане на памет.

Освен това не ми е разрешено да редактирам заглавката.

Разбирам, че за да предотвратите изтичане на памет, трябва да изтриете всички обекти, създадени с помощта на new.

Проблемът ми е, че ако поставя delete в края на моята функция Enqueue(Message msg) така:

void PriorityQ::Enqueue(Message msg)
{
Priorities P = msg.GetPriority();
Node* Location = frontPtr;
Node* PrevLocation = frontPtr;
Node* NewNode = new Node;
NewNode->data = msg;




  if (IsFull())
    throw FullPQ();
  else if (count == 0)
    {
        NewNode->previousPtr = NULL;
        NewNode->nextPtr = NULL;
        count++;
        frontPtr = NewNode;
        rearPtr = NewNode;  
    }
    else
    {
        Priorities  LP = Location->data.GetPriority();          
        while(LP >= P)
        {
            if(Location == NULL)
                break;

            PrevLocation = Location;
            Location = Location->nextPtr;

            if(Location != NULL)
                LP = Location->data.GetPriority();

        }//end line 50 while

             if(Location == NULL)
                {
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;
                    PrevLocation->nextPtr = NewNode;
                    rearPtr = NewNode;
                    count++;

                }
            else
                {
                    PrevLocation = Location->previousPtr;
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;

                    if(PrevLocation == NULL)
                    {
                        Location->previousPtr = NewNode;
                        count++;    
                        frontPtr = NewNode;                         
                    }
                    else
                    {
                        PrevLocation->nextPtr = NewNode;
                        Location->previousPtr = NewNode;
                        count++;                                    
                    }
                }// end line 73 else

    } //end Line 48 else
delete NewNode;
}//end  Enqueue() Function

Получавам грешка при сегментиране при следващото извикване на функцията Enqueue(Message msg) и ако поставя delete в моя деструктор:

PriorityQ::~PriorityQ()
{
 MakeEmpty();

 delete NewNode;

}

дава ми тази грешка priorityq.cpp [Error] 'NewNode' was not declared in this scope

Така че въпросът ми е как мога да предотвратя изтичане на памет в моя код, без да освобождавам обектите си в опашката веднага след създаването им.

Ето пълния файл.

#include "priorityq.h"


PriorityQ::PriorityQ()
{
    frontPtr = NULL;
    rearPtr = NULL;
    count = 0;

}

PriorityQ::~PriorityQ()
{
    MakeEmpty();

  delete NewNode;

}

void PriorityQ::MakeEmpty()
{
    frontPtr = NULL;
    rearPtr = NULL;
    count = 0;
}

void PriorityQ::Enqueue(Message msg)
{
    Priorities P = msg.GetPriority();
    Node* Location = frontPtr;
    Node* PrevLocation = frontPtr;
    Node* NewNode = new Node;
    NewNode->data = msg;




      if (IsFull())
        throw FullPQ();
  else if (count == 0)
    {
        NewNode->previousPtr = NULL;
        NewNode->nextPtr = NULL;
        count++;
        frontPtr = NewNode;
        rearPtr = NewNode;  
    }
    else
    {
        Priorities  LP = Location->data.GetPriority();          
        while(LP >= P)
        {
            if(Location == NULL)
                break;

            PrevLocation = Location;
            Location = Location->nextPtr;

            if(Location != NULL)
                LP = Location->data.GetPriority();

        }//end line 50 while

             if(Location == NULL)
                {
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;
                    PrevLocation->nextPtr = NewNode;
                    rearPtr = NewNode;
                    count++;

                }
            else
                {
                    PrevLocation = Location->previousPtr;
                    NewNode->previousPtr = PrevLocation;
                    NewNode->nextPtr = Location;

                    if(PrevLocation == NULL)
                    {
                        Location->previousPtr = NewNode;
                        count++;    
                        frontPtr = NewNode;                         
                    }
                    else
                    {
                        PrevLocation->nextPtr = NewNode;
                        Location->previousPtr = NewNode;
                        count++;                                    
                    }
                }// end line 73 else

    } //end Line 48 else
delete NewNode;
}//end line 27 Enqueue() Function

void PriorityQ::Dequeue()
{
    if(IsEmpty())
    {
        EmptyPQ Empty;
        throw Empty;
    }

Node* Location = frontPtr;
frontPtr = frontPtr->nextPtr;
Location->nextPtr = NULL;

if(frontPtr != NULL)
{
    frontPtr->previousPtr = NULL;
}
else 
{
    MakeEmpty();
}
if(count != 0)
    count--;

}

void PriorityQ::Purge(Priorities p)
{
if(IsEmpty())
{
    EmptyPQ Empty;
    throw Empty;
}

Node* PurgePtr = frontPtr;
Priorities c = PurgePtr->data.GetPriority();
for(int j = 1; j < count; j++)
{
    if(c == p)
    {
        if(PurgePtr->previousPtr == NULL)
            Dequeue();
        else if( PurgePtr->nextPtr == NULL)
            PurgePtr->previousPtr->nextPtr = NULL;  
        else
        {
            PurgePtr->previousPtr->nextPtr = PurgePtr->nextPtr;
            PurgePtr->nextPtr->previousPtr = PurgePtr->previousPtr;
        }
    }// end line 130 if
    else
    {
        PurgePtr = PurgePtr->nextPtr;
        c = PurgePtr->data.GetPriority();

    }
}// end line 127 for

}

Message PriorityQ::Front() const
{
    if(IsEmpty())
        throw EmptyPQ();
    return frontPtr->data;
}

Message PriorityQ::Rear() const
{
    if(IsEmpty())
        throw EmptyPQ();
    return rearPtr->data;
}

Message PriorityQ::Peek(int n) const
{
    if(n <= (count - 1) )
    {
        Node* PeekPtr = frontPtr;

        for(int j = 0; j < n; j++)
        {
            PeekPtr = PeekPtr->nextPtr;
        }

        return PeekPtr->data;

    }
    else
        throw InvalidPeekPQ();


}

bool PriorityQ::IsFull() const
{
    if(count < 501)
        return false;
    else
        return true;
}

bool PriorityQ::IsEmpty() const
{
    if(count == 0 && frontPtr == NULL)
        return true;
    else
        return false;
}

int PriorityQ::Size() const
{

    return count;
}

person Versanator    schedule 25.03.2016    source източник


Отговори (1)


Проблемът е, че NewNode е локален указател на метода void Priority::Enqueue. Така че не може да бъде достъпен от друг метод.

Когато методът finish NewNode се елиминира и нямате достъп до него.

person B026    schedule 25.03.2016
comment
Това със сигурност е a проблем, но има много, много проблеми. Например, ако IsFull() причини Enqueue до throw, newNode нито ще бъде добавен в списъка, нито deleted. Както и да е, деструкторът трябва да обхожда списъка, delete-ing възли, докато върви. Има и други несвързани грешки, напр. Dequeue не задава rearPtr на nullptr при извличане на последния елемент. - person Tony Delroy; 25.03.2016
comment
@Alberto Как предлагате да започна да създавам нови възли? - person Versanator; 25.03.2016
comment
В момента го прави. Проблемът е, че освобождавате новия възел в последната инструкция, delete NewNode. Трябва да освободите Node в метода void Priority::Dequeue и в деструктора, разбира се, ако е необходимо - person B026; 25.03.2016
comment
MakeEmpty трябва да премине от frontPtr към endPtr и да изтрие всички възли между тях. - person user2913685; 25.03.2016