-2

Есть код, при рантайме выдает ошибку сегментации:

#include <iostream>
using namespace std;
class StudentList
{
private:
    class Student
    {
    private:
        string name;
        int age;
        double height;

    public:
        Student *next;
        explicit Student(string n,int a,double h):
        name(n),
        age(a),
        height(h)
        {}

        string getName()
        {
            return name;
        }
        int getAge()
        {
            return age;
        }
        double getHeight()
        {
            return height;
        }
        ~Student()
        {}
    };

    Student *temp;
public:
    explicit StudentList()
    {
        temp=NULL;
    }

    ~StudentList()
    {

    }

    void list()
    {
        Student* student=temp;
        while(student)
        {
            cout<<temp->getName()<<"\t"<<temp->getAge()<<"\t"<<temp->getHeight()<<"\n";
            temp=temp->next;
        }
        //delete student;
    }

    void insertValue(string name,int age,double height)
    {
        Student *student=new Student(name,age,height);
        student->next=temp;
        temp=student;
    }
};


int main()
{
  StudentList ls;
  ls.insertValue("Falcao",45,1.87);
  ls.insertValue("Jacob",97,3.87);
  ls.list();
}

проблема в функии лист..

1

1 ответ 1

1

У Вас переменная student в методе list проверяется в цикле, но не меняется. Вместо неё меняется поле temp. По идее, нужно заменить temp=temp->next; на что-то вроде student=student->next;. Это то, что сразу бросается в глаза. А чтобы не было именно утечки памяти (seg fault - это не утечка, это попытка обращения к памяти, к которой у программы нет доступа), нужно деструктор для класса StudentList написать. Чтобы он по очереди удалял всех студентов.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.