Как устранить утечку памяти в двусвязном списке? - PullRequest
0 голосов
/ 06 октября 2019

Я пытался устранить утечку памяти с помощью простого имени delete [], но не думаю, что оно было успешно удалено, потому что у меня все еще была утечка памяти. У меня также есть функция DeleteAll (), которая пересекает узлы, но, кажется, не удаляет имя объекта.

Приведенный ниже код находится под функцией добавления, и я думаю, что это может быть причиной утечки моей памяти: в классе CDoublyLinkedList

        CListNode*      work        = NULL;                 // holds head
        CListNode*      prev        = NULL;                 // previous
        CListNode*      newData     = new CListNode();      // instantiation of node class
        char* name = NULL;                                  //char array for name

        /// ________Increase array size of name depending on input
        name = new char[strlen(iName) + 1];
        /// ________Copy string to char
        strcpy_s(name, strlen(iName) + 1, iName);

        newData->SetName(name);     // Set user input to character list

Мой деструктор содержит только функцию удаления всех под той же самойкласс

void DeleteALL()
    {
        CListNode* next;
        CListNode* current;

        current = head;
        while(current != NULL) {
            next = current->GetNext();
            delete current;
            current = next;
        }
        current = NULL;
        head = NULL;
        tail = NULL;
        next = NULL;
    }

это мой основной:

CDoublyLinkedList       element         =       new CDoublyLinkedList;      //list object
Switch(option) {
            /// ____Option Add name
            case '1':
                cout << "Enter name:" << "\t";
                cin >> temp;

                /// ________If input is not 4-25 characters<br></br>
                /// ____________Loop while input is not 4-25 characters<br></br>
                /// ________________Ask for new input<br></br>
                /// ____________End loop<br></br>
                /// ________End if<br></br>
                if((temp.length() >= 3) == false
                    || (temp.length() <= 25) == false) {

                    while((temp.length() >= 3) == false
                        || (temp.length() <= 25) == false) {

                        cout << "Input should be 3-25 characters. Try again." << "\n";
                        cout << "Enter name:" << "\t";
                        cin >> temp;
                    }
                }
                /// ________Add input to list
                element->AddSortList(temp.c_str());

Я удалил объект в моем основном методе с помощью:

if(element != NULL) {
        delete[] element;
        element = NULL;
    }

Класс CNode содержит только get и set

class CListNode
{
private:
    CListNode*          mNext;              // Next item pointer
    CListNode*          mPrev;              // Previous item pointer
    char*               mNameElement;       // List element pointer

public:
    /// <summary>
    /// Node initializer to set as NULL
    /// </summary>
    /// <dt>Date:</dt>
    /// 2019/10/03 Created  by JAC.Tayag (SAT-A)    TRAINING
    CListNode()
    {
        mNext = NULL;
        mPrev = NULL;
    }

    ~CListNode()
    {
        CListNode* next;
        CListNode* current;

        current = mPrev;
        while(current != NULL) {
            next = current->GetNext();
            delete current;
            current = next;
        }
        current = NULL;
        mNext = NULL;
        mPrev = NULL;
        next = NULL;
    }
    /// <summary>
    /// Assign input name
    /// </summary>
    /// <dt>Date:</dt>
    /// 2019/10/03 Created  by JAC.Tayag (SAT-A)    TRAINING
    void SetName(char* iNameElement)
    {
        mNameElement = iNameElement;
    }

    /// <summary>
    /// Assign next pointer
    /// </summary>
    /// <dt>Date:</dt>
    /// 2019/10/03 Created  by JAC.Tayag (SAT-A)    TRAINING
    void SetNext(CListNode* iNext)
    {
        mNext = iNext;
    }

    /// <summary>
    /// Assign previous pointer
    /// </summary>
    /// <dt>Date:</dt>
    /// 2019/10/03 Created  by JAC.Tayag (SAT-A)    TRAINING
    void SetPrev(CListNode* iPrev)
    {
        mPrev = iPrev;
    }

    /// <summary>
    /// Return input name
    /// </summary>
    /// <dt>Date:</dt>
    /// 2019/10/03 Created  by JAC.Tayag (SAT-A)    TRAINING
    char* GetName()
    {
        return mNameElement;
    }

    /// <summary>
    /// Return next pointer
    /// </summary>
    /// <dt>Date:</dt>
    /// 2019/10/03 Created  by JAC.Tayag (SAT-A)    TRAINING
    CListNode* GetNext()
    {
        return mNext;
    }

    /// <summary>
    /// Return previous pointer
    /// </summary>
    /// <dt>Date:</dt>
    /// 2019/10/03 Created  by JAC.Tayag (SAT-A)    TRAINING
    CListNode* GetPrev()
    {
        return mPrev;
    }

1 Ответ

0 голосов
/ 06 октября 2019

Вы можете удалить как один связанный список.

node* element = head;
while( element != 0 ) {
    node* next = element->next;
    delete element;
    element = next;
}
head = 0;
...