Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to fix the Segmentation fault (core dumped) in C++?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please tell me how I can fix this error and how I could avoid it in the future.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading