0

I got segmentation faults when I run the codes below. I noticed that the segmentation fault occurs when I reach another.print(), but I could not figure out why. Can anyone please help?

example.h

class X
{
    private:
        struct Y{
            int a;
            Y* next;
        } *head;
        
    public:
        X();
        X(int k);
        X returnX() const;
        void print() const;
};

example.cpp

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

X::X(){
    head = nullptr;
}

X::X(int k){
    head = new Y;
    head->a = k;
    head->next = nullptr;
}

X X::returnX()const
{
    X test{};
    return test;
}

void X::print() const
{
    cout << "a = "<< head->a << endl;
}

int main(){
    X* init = new X(1);
    X another = init->returnX();
    another.print();
    delete init;

    return 0;
}
kyktyj
  • 3
  • 2
  • 1
    you need to implement copy constructor, assignment operator and destructor for `X`. Even then `another.head` will be null so `print` will crash when you try to dereference `head` – Alan Birtles Mar 05 '22 at 19:44

0 Answers0