Ошибка сегментации из-за указателей - PullRequest
0 голосов
/ 16 марта 2011

У меня были тонны неприятностей, потому что я забыл все правила указателей. Я узнал об указателях 3 года назад и с тех пор не использую их. Я получаю ошибку сегментации в строке contents -> setPrevious(&node) в функции add в файле LinkedList.cpp. Я считаю, что это как-то связано с вызовом функции setPrevious или передачей узла в качестве указателя. Любая помощь будет отличной. Спасибо!

LinkedList.h

#ifndef LINEARNODE_H
#define LINEARNODE_H

#include<iostream>

using namespace std;

class LinearNode
{
    public:
        //Constructor for the LinearNode class that takes no arguments 
        LinearNode();
        //Constructor for the LinearNode class that takes the element as an argument
        LinearNode(int el);
        //returns the next node in the set.
        LinearNode* getNext();
        //returns the previous node in the set
        LinearNode* getPrevious();
        //sets the next element in the set
        void setNext(LinearNode* node);
        //sets the previous element in the set
        void setPrevious(LinearNode* node);
        //sets the element of the node
        void setElement(int el);
        //gets the element of the node
        int getElement();

    private: 
        LinearNode* next;
        LinearNode* previous;
        int element;        
};//ends the LinearNode class

#endif

LinkedList.cpp

#include<iostream>
#include"LinearNode.h"
#include"LinkedList.h"

using namespace std;

//linkedlist constructor for an empty linked list
LinkedList::LinkedList()
{
    count = 0;
    contents = NULL;
}//ends the constructor

//adds an element to the front of the linked list
void LinkedList::add(int element)
{

    int found = 0, current = 0;

    for (int index = 0; index < count; index++)
    {
        if (contents -> getElement() == element)
            found = 1;
        else    
        {

            contents = contents -> getNext();
        }//ends the else statement
    }//ends the while loop

    if ((found == 0) && (count == 0))
    {
        LinearNode node;
        node.setElement(element);
        contents = &node;
        count++;
print();
    }//ends the if statement
    else
    {

        LinearNode node;
        node.setElement(element);
        node.setNext(contents);
        contents -> setPrevious(&node);
        contents = &node;
        count++;
//print();
cout << endl;
    }//ends the found == 0 if statment
}//ends the add function

//this function removes one element from the linked list.
int LinkedList::remove(int element)
{
    int found = 0, result = 0; 
    LinearNode* previous;
    LinearNode* current;

    if (count == 0)
        cout << "The list is empty" << endl;
    else 
    {
        if (contents -> getElement() == element)
        {
            result = contents -> getElement();
            contents = contents -> getNext();
        }//ends the contents.getElement() == element
        else 
        {
            previous = contents;
            current = contents -> getNext();
            for (int index = 0; ( (index < count) && (found == 0) ); index++)
                if (current -> getElement() == element)
                    found = 1;
                else
                {
                    previous = current;
                    current = current -> getNext();
                }//ends the else statement 

            if (found == 0)
                cout << "The element is not in the list" << endl;
            else
            {
                result = current -> getElement();
                previous -> setNext(current -> getNext());
            }//ends else statement  

        }//ends the else stamtement

        count--;
    }//ends the else statement of count == 0
    return result;
}//ends the remove function


void LinkedList::print()
{
    LinearNode* current;
    current = contents; 

    for (int index = 0; index < count; index++)
    {
        cout << current -> getElement() << endl;
        current = current -> getNext();
    }//ends the for loop
}//ends Print function

LinearNode.h

 #ifndef LINEARNODE_H
#define LINEARNODE_H

#include<iostream>

using namespace std;

class LinearNode
{
    public:
        //Constructor for the LinearNode class that takes no arguments 
        LinearNode();
        //Constructor for the LinearNode class that takes the element as an argument
        LinearNode(int el);
        //returns the next node in the set.
        LinearNode* getNext();
        //returns the previous node in the set
        LinearNode* getPrevious();
        //sets the next element in the set
        void setNext(LinearNode* node);
        //sets the previous element in the set
        void setPrevious(LinearNode* node);
        //sets the element of the node
        void setElement(int el);
        //gets the element of the node
        int getElement();

    private: 
        LinearNode* next;
        LinearNode* previous;
        int element;        
};//ends the LinearNode class

#endif

LinearNode.cpp

#include<iostream>
#include"LinearNode.h"

using namespace std;

//Constructor for LinearNode, sets next and element to initialized states
LinearNode::LinearNode()
{
    next = NULL;
    element = 0;
}//ends LinearNode default constructor

//Constructor for LinearNode takes an element as argument.
LinearNode::LinearNode(int el)
{
    next = NULL;
    previous = NULL;
    element = el;
}//ends LinearNode constructor

//returns the next element in the structure
LinearNode* LinearNode::getNext()
{
    return next;
}//ends getNext function

//returns previous element in structure
LinearNode* LinearNode::getPrevious()
{
    return previous;
}//ends getPrevious function

//sets the next variable for the node
void LinearNode::setNext(LinearNode* node)
{
    next = node;

}//ends the setNext function

//sets previous for the node
void LinearNode::setPrevious(LinearNode* node)
{
    previous = node;
}//ends the setPrevious function

//returns element of the node
int LinearNode::getElement()
{
    return element;
}//ends the getelement function

//sets the element of the node
void LinearNode::setElement(int el)
{
    element = el;
}//ends the setElement function

Ответы [ 3 ]

1 голос
/ 17 марта 2011
    LinearNode node;
    node.setElement(element);
    contents = &node;
    count++;

Это создает LinearNode в стеке, contents указывает на этот узел, оставляет область действия в следующем } - что делает недействительным node - и contents после этого указывает на недопустимые данные.

Вам необходимо переосмыслить весь класс - для связанного списка требуется куча памяти, поэтому вам нужно использовать new и delete

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

Некоторые другие ошибки:

  • Отсутствие конструкторов копирования, операторов присваивания и деструкторов
  • Не проверять нулевое значение перед разыменованием указателей
  • Не устанавливать все указатели в null в конструкторах
0 голосов
/ 17 марта 2011

Это большой код для поиска каждой маленькой проблемы, но одна плохая вещь, которая выскакивает, в LinkedList :: add () Там вы объявляете «узел» в стеке, а затем устанавливаете указатель, указывающий на него. Когда add () возвращает, указанный объект становится мусором - вызывается деструктор. Именно такие вещи быстро приводят к ошибкам сегмента.

0 голосов
/ 17 марта 2011

Проблема в том, что вы не выделяете Node в куче, только в стеке.

В add функция

 LinearNode node;
 node.setElement(element);
 contents = &node;
 count++;

Должно быть:

 LinearNode* node = new LinearNode;
 node->setElement(element);
 contents = node;
 count++;
...