[英]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.我正在编写一个组合 2 个向量并对它们进行排序然后打印向量的程序,但我没有使用第三个向量。 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我得到的错误:运行:第 1 行:3 分段错误(核心转储)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.请告诉我如何解决此错误以及将来如何避免它。
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[]
:您的向量没有缓冲区来存储数据,因此您需要在使用
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.现在两者都将分别用
m
和n
个元素进行初始化。
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.如果您使用
at
function 而不是[]
,程序将抛出std::out_of_range
异常,您会突然注意到您正在尝试 go 越界。 But of course at
comes at a performance cost.但当然
at
这是以性能为代价的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.