Vedant Bhandare
Vedant Bhandare

Reputation: 1

Why does this give me segmentation fault?

I am following a course on Udemy and I just learned about smart pointers. This is my code for the challenge the section had-

#include<bits/stdc++.h>
using namespace std;

class Test {
    friend ostream &operator<<(ostream &out,const Test obj);
private:
    int data;
public:
    Test(int d = 0) : data(d)  {cout<<"Test constructor ("<<data<<")\n";}
    ~Test()  {cout<<"Test destructor ("<<data<<")\n";}
};

ostream &operator<<(ostream &out,const Test obj)  {

    out << obj.data;
return out;
}

unique_ptr<vector<shared_ptr<Test>>> create()  {

    unique_ptr<vector<shared_ptr<Test>>> p = make_unique<vector<shared_ptr<Test>>>();

return p;
}

void fill(vector<shared_ptr<Test>> &vec,int num)  {

    int data;
    for(int i = 0; i < num; i++) {
        cout<<"Enter data ["<<i + 1<<"] :\n";
        cin>>data;
        shared_ptr<Test> temp = make_shared<Test>(data);
        //cout<<"Hello\n";
        vec.push_back(temp);
    }

return;
}

void display(vector<shared_ptr<Test>> &vec)  {

    for(const auto &a : vec) cout<<*a;

return;
}

int main()  {

    unique_ptr<vector<shared_ptr<Test>>> u1;
    cout<<"How many data points do you wish to enter?\n";
    int num;
    cin>>num;
    fill(*u1,num);
    display(*u1);

return 0;
}

Running this code gives me segmentation fault and I have figured out there is some problem in the void fill function, but I can't find a solution for it.

Upvotes: 0

Views: 78

Answers (1)

user12002570
user12002570

Reputation: 1

The problem is that smart pointer u1 doesn't point to any object and you're dereferencing it in the call expression fill(*u1,num) which leads to undefined behavior.

//---vvv-------->undefined behavior
fill(*u1,num);  

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior.

So the output that you're seeing(maybe seeing) is a result of undefined behavior. And as i said don't rely on the output of a program that has UB. The program may just crash which is what happens in your crash.

For example, here the program doesn't crash but here it crashes.

So the first step to make the program correct would be to remove UB. Then and only then you can start reasoning about the output of the program.


1For a more technically accurate definition of undefined behavior see this where it is mentioned that: there are no restrictions on the behavior of the program.

Upvotes: 1

Related Questions