今天犯了一个比较蠢的错误
#include <vector>
#include <memory>
using std::vector;
using std::shared_ptr;
int main()
{
shared_ptr<vector<int>> sp;
sp->push_back(1);
return 0;
}
给我报了一个Segmentation fault,什么是seg fault呢?
A segmentation fault occurs when your program attempts to access an area of memory that it is not allowed to access. In other words, when your program tries to access memory that is beyond the limits that the operating system allocated for your program.
Seg faults are mostly caused by pointers that are −
- Used to being properly initialized. (估计写错了,应该是没有正确初始化或者是没有初始化)
- Used after the memory they point to has been reallocated or freed.
- Used in an indexed array where the index is outside of the array bounds.
简言之,就是访问了不该访问的内存,通常关联的代码用到指针,要么指针是野指针、空悬指针,要么下标越界了。
在我的程序里面,我只定义了一个sp,但是这个sp究竟指向谁,我没有说明。那么 push_back
的时候,1
这个元素应该放到哪段内存中呢?自然就报了seg fault。
#include <vector>
#include <memory>
using std::vector;
using std::shared_ptr;
int main()
{
shared_ptr<vector<int>> sp(make_shared<vector<int>>());
sp->push_back(1);
return 0;
}
修改方法:用 make_shared<vector<int>>()
去开辟一段内存,()
里面没参数,所以对 vector
值初始化。