0

this is my simple code to return vector by reference:

#include <bits/stdc++.h>
using namespace std;
    vector<int>& VECTORTEST(){
        vector<int> v;
        v.push_back(10);
        v.push_back(20);
        return v;
    }
    int main()
    {
     vector<int> x = VECTORTEST();

        return 0;
    } 

But I am getting segmentation fault when run this code. Any idea?

Abdus Sattar Bhuiyan
  • 3,016
  • 4
  • 38
  • 72
  • 2
    Turn on your compiler warnings. – chris Mar 31 '19 at 05:45
  • What gave you the impression you should be returning by reference? – StoryTeller - Unslander Monica Mar 31 '19 at 05:45
  • 1
    You should not do this. Any of this. `#include ` is horribly non-standard, and returning a reference to an object with automatic storage duration simply will not work. – Cody Gray - on strike Mar 31 '19 at 05:46
  • 2
    And when you couple [``](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) with [`using namespace std;`](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) it's a quick recipe for name collisions. – StoryTeller - Unslander Monica Mar 31 '19 at 05:47
  • Just return it by value. If you are using a modern C++ version, you will get an automatic move which is not (that) expensive. – Hemil Mar 31 '19 at 06:36
  • The reason is that you are returning a reference to a (possibly) corrupted object. Vectors are automatically deleted on scope exit. And you do access that object. Because `vector x = VECTORTEST();` does a copy. In other words `v` no longer exists when you try to copy it to `x`. Don't ever return by reference unless you're a ninja. – freakish Mar 31 '19 at 08:12

0 Answers0