Question: I need to find the intersection of two arrays and print out the number of elements in the intersection of the two arrays. I must also account for any duplicate elements in both the arrays. So, I decide to take care of the duplicate elements by converting the two arrays into sets and then take the intersection of both the sets. However, I encounter a segmentation fault when I run my code. I'm not sure where this occurs, any way to fix this?

```
#include<iostream>
#include<algorithm>
#include<vector>
#include<set>
using namespace std;
int NumberofElementsInIntersection (int a[], int b[], int n, int m ){
        // Your code goes here
        int i=0,j=0,count=0;
        set<int> s1,s2;
        vector<int> v;
        vector<int>::iterator it;
        for(i=0;i<n;i++)
            s1.insert(a[i]);
        for(i=0;i<m;i++)
            s2.insert(b[i]);
       it=set_intersection(s1.begin(),s1.end(),s2.begin(),s2.end(),v.begin());
       return (it-v.begin());
}

int main(){
    int a[] = {1, 2, 3, 4, 5, 6};
    int b[] = {3, 4, 5, 6, 7};
    cout<<NumberofElementsInIntersection(a,b,6,5);
    return 0;
}

```

Answer: 
`set_intersection` does not allocate memory: <https://en.cppreference.com/w/cpp/algorithm/set_intersection>

You need a `vector` with some space. Change `vector<int> v;` to `vector<int> v(n+m);`

<https://ideone.com/NvoZBu>
I believe you need to provide a std:: back\_inserter(v). No preallocation is required, but it is helpful from an optimization standpoint. See example in

<https://en.cppreference.com/w/cpp/algorithm/set_intersection>