Search code examples
c++arraysvectorstl-algorithm

Segmentation fault while initializing vector by an initialized array in C++


I wanted to use the sort() in the algorithm library in C++. I could find examples for sorting vectors only, thus I am trying to initialize a vector by an initialized array. When executing I am getting a segmentation fault and couldn't figure out what is wrong here in the code I wrote.

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
int n,k,packet[1000],min=0;
scanf("%d",&n);
scanf("%d",&k);

for (int i = 0; i < n; ++i)
{
    scanf("%d",&packet[i]);
    cout<<i<<endl;
}
cout<<"debug";
vector<int> packets(packet,packet+n);
vector<int>::iterator start,stop;
sort(packets.begin(),packets.begin()+n);

min=*(packets.begin())- *(packets.end());
cout<<min;
for (vector<int>::iterator it=packets.begin(); it!=packets.end()-k; ++it)
{
    printf("%d  ",*it );
    if((*(it+k) - *it)<min)
    {
        start=it;
        stop=it+k;
    }
}
printf("%d\n",*stop- *start );

return 0;

}


Solution

  • *(packets.end())
    

    packets.end() returns an iterator to the element, following the last element of the vector.

    Attempting to derefenrence it causes Undefined Behavior.