Почему эта функция вызывает утечку памяти? - PullRequest
0 голосов
/ 04 февраля 2020

Я написал свою собственную структуру данных (Linked List) и использовал ее в приведенном ниже коде. Когда я анализирую программу с помощью valgrind, оба метода pu sh и push_back связанного списка вызывают утечку памяти. Не могли бы вы помочь мне выяснить, почему это происходит?

Связанный список:

template <typename T>
struct Node {
  T data;
  Node *next;
};

/**
 * @brief Simple Linked List implementation
 * 
 * @tparam T 
 */
template <typename T> class List{
private:

public:

    Node<T> *head;


    /**
     * @brief Amount of nodes in the list
     * 
     */
    int length;
    /**
     * @brief Construct a new List object
     * 
     */
    List(){
        head = NULL;
        length = 0;
    }

    /**
     * @brief Add new node to the list and increase size
     * 
     * @param val 
     */
    void push(T val){
        Node<T> *n = new Node<T>();   
        n->data = val;             
        n->next = head;        
        head = n;              
        length++;
    }

    /**
     * @brief Add new node to the end of the list and increase size
     * 
     * @param val 
     */
    void push_back(T val) {
        Node<T> *n = new Node<T>();
        Node<T> * temp = head;
        n->data = val;
        n->next = nullptr;
        if (head) {
            while (temp->next != NULL) {
                temp = temp->next;
            }
            temp->next = n;
        } else {
            head = n;
        }
        length++;
    }

    /**
     * @brief Remove the node from the list and decrease size
     * 
     * @return T 
     */
    T pop(){
      if(head) {
        T p = head->data;
        head = head->next;
        length--;
        return p;
      }
    }


/**
 * @brief Get n-th item on the list
 * 
 * @param index Index of the item 
 * @return T 
 */
    T get(int index) {
        T value_to_return;
        Node<T> * temp = head;
        if (index == 0) {
            return head->data;
        }
        for (int i = 0; i < index; i++) {
            temp = temp->next;
            value_to_return = temp->data;
        }
        return value_to_return;
    }
};

Код, вызывающий ошибки:

/**
 * @file file_reader.h
 * @author Dawid Cyron (software@dawidcyron.me)
 * @brief File with functions used for processing required text files
 * @version 0.1
 * @date 2020-01-26
 * 
 * @copyright Copyright (c) 2020
 * 
 */
#include <vector>
#include "bibliography.h"
#include <fstream>
#include <regex>
#include "list.h"
#include "map.h"


/**
 * @brief Function used for sorting list of bibliography
 * 
 * @param bibliography_list List to sort
 */
void sort_bibliography_list(List<bibliography> bibliography_list) {
    Node <bibliography> * current = bibliography_list.head, * index = NULL;
    bibliography temp;

    if (bibliography_list.head == NULL) {
        return;
    } else {
        while (current != NULL) {
            index = current->next;

            while (index != NULL) {
                if (current->data.author.substr(current->data.author.find(" "), current->data.author.length() - 1) > index->data.author.substr(index->data.author.find(" "), index->data.author.length() - 1)) {
                    temp = current->data;
                    current->data = index->data;
                    index->data = temp;
                }
                index = index->next;
            }
            current = current->next;
        }   
    }
}

/**
 * @brief Funciton used for reading the contents of bibliography file
 * 
 * @param filename Name of the file containing bibliography
 * @return std::vector < bibliography > Vector containing bibliography objects (tag, author, book title), alphabetically sorted by surname
 */
List < bibliography > readBibliographyFile(char * filename) {
    std::ifstream bibliography_file(filename);
    std::string line;
    int line_counter = 0;
    bibliography bib;

    List<bibliography> storage_test;

    if (bibliography_file.is_open()) {
        while (getline(bibliography_file, line)) {
            if (line_counter == 0) {
                if (line == "") {
                    std::cout << "Incorrect data format. Exiting" << std::endl;
                    exit(1);
                }
                bib.label = line;
            } else if (line_counter == 1) {
                if (line == "") {
                    std::cout << "Incorrect data format. Exiting" << std::endl;
                    exit(1);
                }
                bib.author = line;
            } else if (line_counter == 2) {
                if (line == "") {
                    std::cout << "Incorrect data format. Exiting" << std::endl;
                    exit(1);
                }
                bib.book = line;
                storage_test.push_back(bib);
                line_counter = 0;
                // Skip the empty line
                getline(bibliography_file, line);
                continue;
            }
            line_counter++;
        }
    }
    sort_bibliography_list(storage_test);
    return storage_test;
}


/**
 * @brief Function used to load references footer
 * 
 * @param references List of references
 * @param output Reference to the output file
 */
void loadReferenceFooter(List<std::string> references, std::ofstream & output) {
    output << "\nReferences\n \n";;
    for (int i = 0; i < references.length; i++) {
        output << references.get(i);
    }
}

/**
 * @brief Function used to replace cite tags with referenes
 * 
 * @param filename Name of the file containing the text
 * @param data Vector of Bibliography objects (tag, author, book title), has to be sorted by surname
 * @param output_filename Name of the file where the content should be saved
 */
void replaceCites(char * filename, List < bibliography > data, char * output_filename) {
    std::ifstream text_file(filename);
    std::string content;
    content.assign((std::istreambuf_iterator < char > (text_file)), (std::istreambuf_iterator < char > ()));
    //std::map < std::string, int > map;
    std::ofstream output(output_filename);
    int cite_counter = 1;
    List<std::string> references;
    Hashtable<std::string, int> hash_table; 
    HashtableItem<std::string, int> * item;

    for (int i=0; i < data.length; i++) {
        std::smatch matches;
        std::regex regex("\\\\cite\\{" + data.get(i).label + "\\}");
        std::regex_search(content, matches, regex);
        if (!matches.empty()) {
            item = hash_table[data.get(i).label];
            if (item != nullptr) {
                content = std::regex_replace(content, regex, "[" + std::to_string(item->Value()) + "]");
            } else {
                content = std::regex_replace(content, regex, "[" + std::to_string(cite_counter) + "]");
                references.push_back("[" + std::to_string(cite_counter) + "] " + data.get(i).author + ", " + data.get(i).book + "\n");
                hash_table.Add(data.get(i).label, cite_counter);
                cite_counter++;
            }
        }
    }
    output << content << std::endl;
    text_file.close();
    loadReferenceFooter(references, output);
    output.close();
}

Насколько мне известно, данные структура должна работать правильно. Я попытался создать деструктор, который прошел бы по всем узлам связанного списка и удалил их один за другим, но это тоже не сработало (фактически, это привело к тому, что приложение даже не запустилось).

Ответы [ 4 ]

2 голосов
/ 05 февраля 2020

Память утечка, потому что нет деструктора, чтобы освободить выделенные Node с. Аскер отмечает, что они удалили деструктор, потому что программа потерпела крах, когда у них был тот. Это ошибка, которую нужно было устранить, потому что правильно использовать деструктор.

Решение

Отложите деструктор обратно и решите, почему деструктор вызвал программу к sh .

Решение для Решения

List нарушает Правило Трех . Это означает, что когда List копируется, и у вас есть два объекта, каждый из которых указывает на одну и ту же головку Node. Этот Node может быть delete d только один раз, и оба объекта будут пытаться delete его в деструкторе List. Рано или поздно программа умирает мучительной смертью.

Обычно вы можете заменить проходы по значению проходами по ссылке, а затем запретить копирование с помощью delete специальных функций-членов. Например. добавьте

List(const List & src) = delete;
List& operator=(List src) = delete;

к List и дождитесь, когда компилятор начнет кричать о копировании List при удалении специальных функций копирования. Замените все проходы по значению проходами по ссылке.

К сожалению

List<bibliography> readBibliographyFile(char * filename)

возвращает по значению. Возврат по локальной ссылке обречен . Локальная переменная выходит из области видимости и уничтожается, оставляя вам ссылку на недопустимый объект. Это означает, что вы должны сделать это трудным путем:

Реализация всех трех специальных функций-членов:

// destructor
~List()
{
    while (head)
    {
        Node<T> * temp = head->next;
        delete head;
        head = temp;
    }
}

// copy constructor
List(const List & src): head(NULL), length(src.length)
{
    Node<T> ** destpp = &head; // point at the head.
                               // using a pointer to a pointer because it hides 
                               // the single difference between head and a Node's 
                               // next member: their name. This means we don't need 
                               // any special cases for handling the head. It's just 
                               // another pointer to a Node.
    Node<T> * srcnodep = src.head;
    while (srcnodep) //  while there is a next node in the source list
    {
        *destpp = new Node<T>{srcnodep->data, NULL}; // copy the node and store it at 
                                                     // destination
        destpp = &((*destpp)->next); // advance destination to new node
        srcnodep = srcnodep->next; // advance to next node in source list
    }
}

List& operator=(List src) // pass list by value. It will be copied
{
    length = src.length; // Technically we should swap this, but the copy 
                         // is gonna DIE real soon.
    // swap the node lists. use std::swap if you can.
    Node<T> * temp = head;
    head = src.head; 
    src.head = temp;

    // now this list has the copy's Node list and the copy can go out of scope 
    // and destroy the list that was in this List.

    return *this;
}

Примечания

operator= использует преимущества Копирование и замена идиомы . Часто это не самое быстрое решение, но его легко написать и почти невозможно ошибиться. Я начинаю с Copy и Swap и выполняю миграцию на что-то более быстрое только тогда, когда профилирование производительности кода показывает, что я должен, и это почти никогда не происходит.

Приходит также и трюк с указателем на указатель, используемый в конструкторе копирования. очень удобно, когда вставляет и удаляет элементы списка.

Знает и понимает Правило Трех и его друзей . Вы не можете писать сложные и эффективные программы на C ++ без него. Вполне возможно, что это задание было дано, по крайней мере, частично, чтобы заставить вас выучить его.

2 голосов
/ 04 февраля 2020

"Почему эта функция вызывает утечку памяти?" - Просто: вы выделяете память с помощью new, которую никогда не освобождаете с помощью delete.

. В современном C ++ вы, как правило, предпочитаете использовать умные указатели (в данном случае std::unique_ptr) и / или контейнерные классы. чем делать ручное управление памятью с new / delete.

0 голосов
/ 04 февраля 2020

Хорошо, я узнал, где проблема для меня, и я сделал довольно грязное исправление, но оно работает. Для тех, кто рассказал мне о том, как заботиться о коде, я улучшу его, как только закончу свои экзамены, но с таким жестким сроком мне просто нужно было самое быстрое решение. Вы можете найти его ниже.

Я добавил эту функцию в список:

void clear() {
    while (head) {
        Node<T> * temp = head->next;
        delete head;
        head = temp;
        length--;
    }
}

И затем в конце функции replaceCites я вызываю:

data.clear();
references.clear();
0 голосов
/ 04 февраля 2020

Если вы можете выбрать, какой тип списка вы реализуете, вот версия, похожая на вектор (по сравнению с вашим связанным списком)

#include <cstdlib>
#include <iostream>

template <typename T>
struct list final {
  T* values;
  std::size_t capacity, size;

  list() : values{nullptr}, capacity{0u}, size{0u} {}
  ~list() { std::free(values); }
  void push_back(T value) {
    if (size == capacity) {
      capacity = (capacity + 1) * 2;
      if (void* mem = std::realloc(values, capacity * sizeof(T))) {
        values = reinterpret_cast<T*>(mem);
      } else {
        throw std::bad_alloc();
      }
    }
    values[size++] = value;
  }

  void pop_back() { --size; }
};

int main() {
  list<int> integers;
  for (int i = 0; i < 10; ++i) {
    integers.push_back(i);
  }
  for (int i = 0; i < integers.size; ++i) {
    std::cout << integers.values[i] << std::endl;
  }
}
...