Passing vector by reference: Segmentation fault : <p>I'm trying to get the following code for merge sort work with vectors instead of C style arrays and I'm having a hard time figuring out why it crashes with segmentation fault. Can someone help me out in understanding the problem here?</p>

<pre><code>#include &lt;bits/stdc++.h&gt;
using namespace std;

void merge(vector&lt;int&gt;&amp; a, int l, int m, int r) {
    vector&lt;int&gt; L;
    vector&lt;int&gt; R;

    for (int i = 0; i &lt;= m; i++)
        L.push_back(a[i]);
    for (int i = m+1; i &lt;= r; i++)
        R.push_back(a[i]);

    int i = 0, j = 0; // Initial index of first and second subarray
    int k = l;  // Initial index of merged subarray
    while (i &lt; L.size() &amp;&amp; j &lt; R.size()) {
        if (L[i] &lt;= R[j]) {
            a[k] = L[i];
            i++;
        }
        else {
            a[k] = R[j];
            j++;
        }
        k++;
    }

    // Filling leftovers
    while (i &lt; L.size()) {
        a[k] = L[i];
        k++;
        i++;
    }
    while (j &lt; R.size()) {
        a[k] = R[j];
        k++;
        j++;
    }
}

void merge_sort(vector&lt;int&gt;&amp; a, int l, int r) {
    if (l &lt; r) {
        int m = l + (r-l) / 2; // Avoids integer overflow.
        merge_sort(a, l, m);
        merge_sort(a, m+1, r);
        merge(a, l, m, r);
    }
}

int main()
{
    vector&lt;int&gt; a = {2, 4, 1, 5, 3, 9};
    int size = a.size();    
    merge_sort(a, 0, size-1);
    for (int i = 0; i &lt; size; i++)
        cout &lt;&lt; a[i] &lt;&lt; ' ';
    cout &lt;&lt; endl;
    return 0;
}
</code></pre>
