Reputation: 439
I'm writing a program that combines 2 vectors and sorts them and then prints the vector but I'm not using a third vector. Instead I'm combining one vector with another and then sorting the combined vector. But I get a error called "Segmentation fault".
here's the code:
#include<bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
ios_base::sync_with_stdio(0);
cin.tie(0);
int m,n;
cin >> m >> n;
vector<int> nums1, nums2;
for(int i=0; i<m; i++) cin >> nums1[i];
for(int i=0; i<n; i++) cin >> nums2[i];
for(int i=0; i<n; i++){ // nums2
nums1.push_back(nums2[i]); // I am adding all the elements present in nums2 into nums1
}
sort(nums1.begin(), nums1.end());
for(int i=0; i<(m+n); i++) cout << nums1[i] << " ";
return 0;
}
The error I get: run: line 1: 3 Segmentation fault (core dumped) LD_LIBRARY_PATH=/usr/local/gcc-8.3.0/lib64 ./a.out
Please tell me how I can fix this error and how I could avoid it in the future.
Upvotes: 0
Views: 4101
Reputation: 3672
Here:
vector<int> nums1, nums2;
for(int i=0; i<m; i++) cin >> nums1[i]; // this causes undefined behavior
for(int i=0; i<n; i++) cin >> nums2[i]; // also this one
your vectors have no buffer to store data so you need to do this before using operator[]
:
vector<int> nums1(m), nums2(n);
nums1.push_back(2); // will add 2 to the back of nums1 so size will become m + 1
nums2.push_back(6); // will add 6 to the back of nums2 so size will become n + 1
// you can do as many push_backs as you want until
// your computer runs out of memory
Now both will be initialized with m
and n
number of elements respectively.
If you used the at
function instead of []
, the program would throw a std::out_of_range
exception and you would suddenly notice that you were trying to go out of bounds. But of course at
comes at a performance cost.
Upvotes: 3